package com.ysd.lis.service.lab.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.DataBaseType;
import com.ysd.common.GetApplicationContext;
import com.ysd.common.Result;
import com.ysd.lis.aspect.SysEventLog;
import com.ysd.lis.entity.*;
import com.ysd.lis.entity.bac.*;
import com.ysd.lis.entity.lab.*;
import com.ysd.lis.entity.samsto.SamstoSpecboxOrder;
import com.ysd.lis.entity.samsto.SamstoSpecboxOrderReq;
import com.ysd.lis.mapper.bac.*;
import com.ysd.lis.mapper.lab.*;
import com.ysd.lis.mapper.sys.SysInterfaceMapper;
import com.ysd.lis.mapper.sys.SysOrgDepartmentMapper;
import com.ysd.lis.request.*;
import com.ysd.lis.request.lab.*;
import com.ysd.lis.service.PubEmployeeService;
import com.ysd.lis.service.SysBasDictDetailService;
import com.ysd.lis.service.SysParamValueService;
import com.ysd.lis.service.SysRuleSetService;
import com.ysd.lis.service.lab.*;
import com.ysd.util.IncrementalNumberGenerator;
import com.ysd.util.RedisUserManager;
import com.ysd.util.ToolsUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * <p>
 * 检验申请主表 服务实现类
 * </p>
 *
 * @author HuiXing
 * @since 2023-12-26
 */
@Service
public class LabReqMainServiceImpl extends ServiceImpl<LabReqMainMapper, LabReqMain> implements LabReqMainService {

    @Autowired
    private LabReqMainMapper labReqMainMapper;

    @Autowired
    private LabReqMainQueryMapper labReqMainQueryMapper;
    @Autowired
    SysBasDictDetailService dictDetailService;
    @Autowired
    PubEmployeeService pubEmployeeService;
    @Autowired
    SysOrgDepartmentMapper organizationMapper;
    @Autowired
    LabReqStateMapper labReqStateMapper;
    @Autowired
    LabReqAdditionsMapper labReqAdditionsMapper;
    @Autowired
    LabMaininfoMapper labMaininfoMapper;
    @Autowired
    LabReqdetailMapper labReqdetailMapper;
    @Autowired
    LabReqdetailDelMapper labReqdetailDelMapper;
    @Autowired
    LabReqdetailService labReqdetailService;
    @Autowired
    LabReqdetailDelService labReqdetailDelService;
    @Autowired
    BacReqPurposeMapper bacReqPurposeMapper;
    @Autowired
    BacReqPurposeDetailMapper bacReqPurposeDetailMapper;//微生物检验目的首选备选方案
    @Autowired
    BacWorkFlowMapper bacWorkFlowMapper;//方案流程
    @Autowired
    BacWorkFlowNodeMapper bacWorkFlowNodeMapper;//方案流程节点
    @Autowired
    BacCultureCombinationMapper bacCultureCombinationMapper;//培养基组合
    @Autowired
    BacCultureCombinaRelMapper bacCultureCombinaRelMapper;//培养基组合明细
    @Autowired
    BacCultureMediumMapper bacCultureMediumMapper;//培养基
    @Autowired
    BacTestWorkFlowMapper bacTestWorkFlowMapper;//检验选用方案
    @Autowired
    BacTestWorkFlowNodeMapper bacTestWorkFlowNodeMapper;//检验选用方案对用节点
    @Autowired
    BacTestCultureMediumMapper bacTestCultureMediumMapper;//检验选用培养基
    @Autowired
    SysRuleSetService sysRuleSetService;//编码规则服务
    @Autowired
    BacReqPurposeFeeItemMapper bacReqPurposeFeeItemMapper;
    @Autowired
    private LabFeeItemMapper labFeeItemMapper;//申请项目
    @Autowired
    SysOrgDepartmentMapper sysOrgDepartmentMapper;
    @Autowired
    SysBasDictDetailService sysBasDictDetailService;
    @Autowired
    LabReqStateService labReqStateService;
    @Autowired
    LabProcessSetService labProcessSetService;
    @Autowired
    LabMainInfoServiceBakImpl labMainInfoServiceBak;
    @Autowired
    SysParamValueService sysParamValueService;
    @Autowired
    LabProcessSetMapper labProcessSetMapper;
    @Autowired
    LabTatGroupruleService labTatGroupruleService;
    @Autowired
    LabFinanceSalesFeeitemService labFinanceSalesFeeitemService;
    @Autowired
    LabTatNodeService labTatNodeService;
    @Autowired
    LabTatNodeMapper labTatNodeMapper;
    @Autowired
    LabHisReqMapper labHisReqMapper;

    @Autowired
    LabReqMainService labReqMainService;
    @Autowired
    SysInterfaceMapper sysInterfaceMapper;

    @Autowired
    LabMainStateService labMainStateService;

    @Autowired
    LabReqMainBacServiceImpl labReqMainBacService;
    @Autowired
    LabProcessSetMapper processSetMapper;

    @Override
    public Result findLabReqMainPageList(LabMaininfoPageDto maininfoPageDto) {

        LambdaQueryWrapper<LabReqMain> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(LabReqMain::getDelFlag, 0);
        Timestamp startTime = Timestamp.valueOf(maininfoPageDto.getSampledaBegin());
        Timestamp endTime = Timestamp.valueOf(maininfoPageDto.getSampledaEnd());
        //申请时间
        lambdaQueryWrapper.ge(LabReqMain::getReqTime, startTime);
        lambdaQueryWrapper.le(LabReqMain::getReqTime, endTime);
        if (StringUtils.isNotBlank(maininfoPageDto.getReqNoS()) && StringUtils.isNotBlank(maininfoPageDto.getReqNoE())) {
            lambdaQueryWrapper.ge(LabReqMain::getReqNo, maininfoPageDto.getReqNoS());
            lambdaQueryWrapper.le(LabReqMain::getReqNo, maininfoPageDto.getReqNoE());
        }
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getReqNo()), LabReqMain::getReqNo, maininfoPageDto.getReqNo());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getPatNo()), LabReqMain::getPatNo, maininfoPageDto.getPatNo());
        if (com.baomidou.mybatisplus.core.toolkit.StringUtils.isNotBlank(maininfoPageDto.getPatNa())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(LabReqMain::getPatNa, maininfoPageDto.getPatNa()).or().like(LabReqMain::getPatPyName, maininfoPageDto.getPatNa()));
        }
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getBedNo()), LabReqMain::getBedNo, maininfoPageDto.getBedNo());
        if (StringUtils.isNotBlank(maininfoPageDto.getSamplingTime())) {
            Timestamp samplingStart = Timestamp.valueOf(maininfoPageDto.getSamplingTime() + " 00:00:00");
            Timestamp samplingEnd = Timestamp.valueOf(maininfoPageDto.getSamplingTime() + " 23:59:59");
            lambdaQueryWrapper.ge(LabReqMain::getSamplingTime, samplingStart);
            lambdaQueryWrapper.le(LabReqMain::getSamplingTime, samplingEnd);
        }
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getFeeType()), LabReqMain::getFeeType, maininfoPageDto.getFeeType());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getReqDept()), LabReqMain::getReqDept, maininfoPageDto.getReqDept());
        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getPatType()), LabReqMain::getPatType, maininfoPageDto.getPatType());

        lambdaQueryWrapper.eq(StringUtils.isNotBlank(maininfoPageDto.getSex()), LabReqMain::getSex, maininfoPageDto.getSex());

        //过滤无条码
        if (maininfoPageDto.getIsFilterNoSpecCode()) {
            lambdaQueryWrapper.isNotNull(LabReqMain::getReqNo);
        }
        List<LabReqMain> labReqMainPage = labReqMainMapper.selectList(lambdaQueryWrapper);

        LambdaQueryWrapper<SysOrgDepartment> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.eq(SysOrgDepartment::getDelFlag, 0);
        List<SysOrgDepartment> sysOrgDepartments = sysOrgDepartmentMapper.selectList(lambdaQueryWrapper1);

        labReqMainPage.forEach(a -> {
            if (StringUtils.isNotEmpty(a.getReqDept())) {
                Optional<SysOrgDepartment> first = sysOrgDepartments.stream().filter(s -> StringUtils.isNotBlank(s.getCode())).filter(s -> s.getCode().equals(a.getReqDept())).findFirst();
                if (first.isPresent()) {
                    a.setReqDeptNa(first.get().getName());
                }
            }
        });
        List<LabReqMain> returnList = new ArrayList<>();
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(labReqMainPage)) {
            if (StringUtils.isNotEmpty(maininfoPageDto.getFeeName())) {
                Set<String> set = new HashSet<>();
                List<String> list = Arrays.asList(maininfoPageDto.getFeeName().split(","));
                for (String a : list) {
                    List<LabReqMain> collect = labReqMainPage.stream().filter(p -> StringUtils.isNotEmpty(p.getReqPurpose()) && p.getReqPurpose().contains(a)).collect(Collectors.toList());
                    returnList.addAll(collect);
                }
                ;
            } else {
                returnList = labReqMainPage;
            }
        }
        returnList = returnList.stream().distinct().collect(Collectors.toList());
        return Result.succ(1, "查询成功", returnList);
    }

    @Override
    public Result getReqMainByReqNo(LabReqMain reqMain) throws JsonProcessingException {
        if (ToolsUtils.isEmpty(reqMain)) {
            return Result.fail("入参不可为空");
        }
        if (ToolsUtils.isEmpty(reqMain.getReqNo())) {
            return Result.fail("条码号----入参不可为空");
        }
        SysParamParam sysp1 = new SysParamParam();
        sysp1.setParamCode("xtxxcs");
        sysp1.setField("bbthsfscsqbxx");
        List<SysParamFieldValueDto> r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
        if (r1.isEmpty() || !r1.get(0).getValue().equals("1")) {
            LambdaQueryWrapper<LabReqMainQuery> mainQueryWrapper = new LambdaQueryWrapper<>();
            mainQueryWrapper.eq(LabReqMainQuery::getReqNo, reqMain.getReqNo());
            List<LabReqMainQuery> labReqMainList = labReqMainQueryMapper.selectList(mainQueryWrapper);
            for (LabReqMainQuery labReqMainQuery : labReqMainList) {
                if (labReqMainQuery.getDelFlag().equals(1)) {
                    return Result.fail("该条码号已作废");
                } else {
                    if (StringUtils.isNotBlank(labReqMainQuery.getState()) && labReqMainQuery.getState().equals("150")) {
                        return Result.fail("该条码号已作废");
                    }
                }
            }
        }
        MPJLambdaWrapper<LabReqMain> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabReqMain.class);
        queryWrapper.selectAs("ld", LabReqdetail::getFeeCode, LabReqMain::getFeeCode);
        queryWrapper.selectAs("ld", LabReqdetail::getFeeName, LabReqMain::getFeeName);
        queryWrapper.selectAs("ld", LabReqdetail::getHisReqId, LabReqMain::getHisReqId);
        queryWrapper.leftJoin(LabReqdetail.class, "ld", p -> p.eq(LabReqdetail::getReqNo, LabReqMain::getReqNo).eq(LabReqdetail::getDelFlag, 0));
        queryWrapper.eq(LabReqMain::getDelFlag, 0).eq(LabReqMain::getReqNo, reqMain.getReqNo());
        List<LabReqMain> list = labReqMainMapper.selectList(queryWrapper);

        if (CollectionUtils.isEmpty(list)) {
            AddLabMaininfo paramObj = new AddLabMaininfo();
            paramObj.setReqNo(reqMain.getReqNo());
            Result apiReqMainInfo = labMainInfoServiceBak.getApiReqMainInfo(paramObj);
            if ("400".equals(apiReqMainInfo.getStatus().get("code") + "")) {
                throw new RuntimeException(apiReqMainInfo.getStatus().get("msg") + "");
            }
            LabReqMain reqMainEntry = labMainInfoServiceBak.getLabReqMainEntity(reqMain.getReqNo());
            if (BeanUtil.isNotEmpty(reqMainEntry)) {
                list.add(reqMainEntry);
            }
        }

        List<Map<String, Object>> sexList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("Sex").getData();
        for (LabReqMain m : list) {
            if (StringUtils.isNotBlank(m.getSex()) && org.apache.commons.collections4.CollectionUtils.isNotEmpty(sexList)) {
                sexList.stream().filter(a -> a.get("code").equals(m.getSex())).findFirst().ifPresent(stringObjectMap -> m.setSexNa((String) stringObjectMap.get("name")));
            }
        }
        List<LabReqMain> listResult = new ArrayList<>();
        if (ToolsUtils.isNotEmpty(list)) {
            LabReqMain combinedLabReqMain = new LabReqMain();
            combinedLabReqMain.setFeeCode(list.stream().map(LabReqMain::getFeeCode).collect(Collectors.joining(",")));
            combinedLabReqMain.setFeeName(list.stream().map(LabReqMain::getFeeName).collect(Collectors.joining(",")));
            LabReqMain labReqMain = list.get(0);
            labReqMain.setFeeCode(combinedLabReqMain.getFeeCode());
            labReqMain.setFeeName(combinedLabReqMain.getFeeName());
            listResult.add(labReqMain);
        }

        //添加系统参数判断是否需要重新获取计费信息，（东北双塔天健接口需求）2025-03-18
        /*添加系统参数判断是否需要重新获取计费信息*/
        SysParamParam sysp111 = new SysParamParam();
        sysp111.setParamCode("xtxxcs");
        sysp111.setField("smsjsfxycxlqsq");
        List<SysParamFieldValueDto> xtcs1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp111);
        //40为标本采集，标本采集不计费，2025-06-17 双塔医院需求
        if (!xtcs1.isEmpty()&&!"40".equals(reqMain.getState())) {
            if (xtcs1.get(0).getValue().equals("1")) {
                LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(SysInterface::getDelFlag, 0);
                wrapper.eq(SysInterface::getIsEnable, 1);
                wrapper.eq(SysInterface::getOrgId, reqMain.getOrgId());
                List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
                List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());
                SysUser sysUser = RedisUserManager.getUser();
                //标本签收计费通过系统参数配置
                if (CollectionUtils.isNotEmpty(collect)) {
                    for (String webUrl : collect) {

                        Map<String, Object> updateMap = new HashMap<>();
                        updateMap.put("status", "0304");
                        updateMap.put("reqNo", reqMain.getReqNo());
                        updateMap.put("username", sysUser.getUsername());
                        updateMap.put("realname", sysUser.getRealname());
                        updateMap.put("orgId", sysUser.getOrgId());
                        updateMap.put("patType", reqMain.getPatType());
                        String addFeeUrl = webUrl + "/public/beginCheckAddFee";
                        String body = HttpUtil.createPost(addFeeUrl).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();
                        JSONObject jsonObject = new JSONObject(body);
                        JSONObject status = jsonObject.getJSONObject("status");
                        String code = status.get("code").toString();
                        if ("400".equals(code)) {
                            return Result.fail(jsonObject.getStr("data"));
                        }
                    }
                }
            }
        }
        if (listResult.size() > 0) {
            return Result.succ(listResult);
        } else {
            return Result.fail("未查询到数据");
        }
    }

    @Override
    public Result createSamplingDetail(LabReqMain reqMain) throws JsonProcessingException {
        if (ToolsUtils.isEmpty(reqMain)) {
            return Result.fail("入参不可为空");
        }
        if (ToolsUtils.isEmpty(reqMain.getReqNo())) {
            return Result.fail("条码号----入参不可为空");
        }
        //修改申请表信息状态
        LambdaQueryWrapper<LabProcessSet> processSetWrapper = new LambdaQueryWrapper<>();
        processSetWrapper.eq(LabProcessSet::getDelFlag, 0);
        processSetWrapper.eq(LabProcessSet::getCode, "40");
        List<LabProcessSet> processSets = processSetMapper.selectList(processSetWrapper);

        String value = "";
        if (CollectionUtils.isNotEmpty(processSets)) {
            value = processSets.get(0).getNodeName();
        }
        if (ToolsUtils.isEmpty(value)) {
            return Result.fail("未获取到词典状态信息----请检查系统设置中是否配置检验状态");
        }
        SysUser sysUser = RedisUserManager.getUser();
        if (ToolsUtils.isEmpty(sysUser.getHisEmployeeCode())) {
            return Result.fail("员工编号不可为空----请在系统设置中对应员工编号");
        }
        if (ToolsUtils.isEmpty(sysUser.getRealname())) {
            return Result.fail("员工姓名不可为空----请在系统设置中对应员工姓名");
        }
        if (ToolsUtils.isEmpty(sysUser.getHisEmployeeId())) {
            return Result.fail("员工ID不可为空----请在系统设置中对应员工编号");
        }
        Result re = pubEmployeeService.getHisEmployeeInfoById(sysUser.getHisEmployeeId());
        if (ToolsUtils.isEmpty(re.getData())) {
            return Result.fail("获取员工员工信息异常");
        }
        PubEmployee employee = (PubEmployee) re.getData();
        if (ToolsUtils.isEmpty(employee.getDeptId())) {
            return Result.fail("员工科室不可为空----请在系统设置中设置对应科室");
        }
        SysOrgDepartment orgDepartment = organizationMapper.selectById(employee.getDeptId());
        if (ToolsUtils.isEmpty(orgDepartment)) {
            return Result.fail("科室信息不可为空----请在系统设置中设置员工科室信息");
        }
        if (ToolsUtils.isEmpty(orgDepartment.getName())) {
            return Result.fail("科室名称不可为空----请在系统设置中设置员工科室信息");
        }
        if (ToolsUtils.isEmpty(reqMain.getBatchNo())) {
            reqMain.setBatchNo(IncrementalNumberGenerator.generateIncrementalNumber8());
        }
        int a = 0;
        LambdaUpdateWrapper<LabReqMain> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(LabReqMain::getState, "40").set(LabReqMain::getStateNa, value);
        lambdaUpdateWrapper.set(LabReqMain::getIsSampling, 1).set(LabReqMain::getSamplingDoctor, sysUser.getHisEmployeeCode());
        lambdaUpdateWrapper.set(LabReqMain::getSamplingDoctorNa, sysUser.getRealname());
        lambdaUpdateWrapper.set(LabReqMain::getSamplingDeptNa, orgDepartment.getName());
        lambdaUpdateWrapper.set(LabReqMain::getSamplingDept, employee.getDeptId());
        lambdaUpdateWrapper.set(LabReqMain::getSamplingTime, new Date());
        lambdaUpdateWrapper.eq(LabReqMain::getReqNo, reqMain.getReqNo());
        a = labReqMainMapper.update(null, lambdaUpdateWrapper);
        String reqId = reqMain.getId();
        LambdaQueryWrapper<LabReqState> queryStateWrapper = new LambdaQueryWrapper<>();
        queryStateWrapper.eq(LabReqState::getReqMainId, reqId).eq(LabReqState::getOrgId, sysUser.getOrgId()).eq(LabReqState::getDelFlag, 0);
        List<LabReqState> listState = labReqStateMapper.selectList(queryStateWrapper);
        //存储当前标本状态
        LabReqState labReqState = new LabReqState();
        labReqState.setOrgId(sysUser.getOrgId());
        labReqState.setStateCode("40");
        labReqState.setStateValue(value);
        labReqState.setRemark(value);
        labReqState.setReqMainId(reqId);
        labReqState.setBatchNo(reqMain.getBatchNo());
        labReqState.setSeq((long) (listState.size() + 1));
        a = labReqStateMapper.insert(labReqState);
        Result result1 = this.getReqMainByReqNo(reqMain);
        List<LabReqMain> labReqMain = (List<LabReqMain>) result1.getData();

        LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysInterface::getDelFlag, 0);
        wrapper.eq(SysInterface::getIsEnable, 1);
        wrapper.eq(SysInterface::getOrgId, reqMain.getOrgId());
        List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
        List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());

        //标本签收
//        if (CollectionUtils.isNotEmpty(collect)) {
//            for (String webUrl : collect) {
//                //调用修改状态接口
//                String updateUrl = webUrl + "/public/updateReportStatus";
//                Map<String, Object> updateMap = new HashMap<>();
//                updateMap.put("status", "0304");
//                updateMap.put("reqNo", reqMain.getReqNo());
//                updateMap.put("patType", reqMain.getPatType());
//                updateMap.put("username", sysUser.getUsername());
//                updateMap.put("realname", sysUser.getRealname());
//                updateMap.put("chargeType", "1");
//                HttpUtil.createPost(updateUrl).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();
//                //调用执行医嘱确费接口
//                if ("3".equals(reqMain.getPatType())) {
//                    String yzqfUrl = webUrl + "/yzqf";
//                    HttpUtil.createPost(yzqfUrl).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();
//
////                    String updateUrlHl7 = webUrl + "/confimReceiveFee";
////                    HttpUtil.createPost(updateUrlHl7).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();
//                }
////                String hl7Url = webUrl + "/public/sampleReceive";
////                HttpUtil.createPost(hl7Url).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();
//            }
//        }
        if (a > 0) {
            return Result.succ(1, reqMain.getBatchNo(), labReqMain);
        } else {
            return Result.fail("采样失败");
        }
    }

    //标本接收
    @Override
    public Result createCollectionDetail(LabReqMain reqMain) throws JsonProcessingException {
        if (ToolsUtils.isEmpty(reqMain)) {
            return Result.fail("入参不可为空");
        }
        if (ToolsUtils.isEmpty(reqMain.getReqNo())) {
            return Result.fail("条码号----入参不可为空");
        }

        if (StringUtils.isBlank(reqMain.getActStateCode())) {
            return Result.fail("状态值为空");
        }
        //修改申请表信息状态
        LambdaQueryWrapper<LabProcessSet> processSetWrapper = new LambdaQueryWrapper<>();
        processSetWrapper.eq(LabProcessSet::getDelFlag, 0);
        processSetWrapper.eq(LabProcessSet::getCode, reqMain.getActStateCode());
        List<LabProcessSet> processSets = processSetMapper.selectList(processSetWrapper);

        String value = "";
        if (CollectionUtils.isNotEmpty(processSets)) {
            value = processSets.get(0).getNodeName();
        }
        if (ToolsUtils.isEmpty(value)) {
            return Result.fail("未获取到词典状态信息----请检查系统设置中是否配置检验状态");
        }
        SysUser sysUser = RedisUserManager.getUser();
        if (ToolsUtils.isEmpty(sysUser.getUsername())) {
            return Result.fail("员工编号不可为空----请在系统设置中对应员工编号");
        }
        if (ToolsUtils.isEmpty(sysUser.getRealname())) {
            return Result.fail("员工姓名不可为空----请在系统设置中对应员工姓名");
        }
        /*if (ToolsUtils.isEmpty(sysUser.getHisEmployeeId())) {
            return Result.fail("员工ID不可为空----请在系统设置中对应员工编号");
        }
        Result re = pubEmployeeService.getHisEmployeeInfoById(sysUser.getHisEmployeeId());
        if (ToolsUtils.isEmpty(re.getData())) {
            return Result.fail("获取员工员工信息异常");
        }
        PubEmployee employee = (PubEmployee) re.getData();
        if (ToolsUtils.isEmpty(employee.getDeptId())) {
            return Result.fail("员工科室不可为空----请在系统设置中设置对应科室");
        }
        SysOrgDepartment orgDepartment = organizationMapper.selectById(employee.getDeptId());
        if (ToolsUtils.isEmpty(orgDepartment)) {
            return Result.fail("科室信息不可为空----请在系统设置中设置员工科室信息");
        }
        if (ToolsUtils.isEmpty(orgDepartment.getName())) {
            return Result.fail("科室名称不可为空----请在系统设置中设置员工科室信息");
        }*/
        if (ToolsUtils.isEmpty(reqMain.getBatchNo())) {
            reqMain.setBatchNo(IncrementalNumberGenerator.generateIncrementalNumber8());
        }
        int a = 0;
        LambdaUpdateWrapper<LabReqMain> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.set(LabReqMain::getState, reqMain.getActStateCode());
        lambdaUpdateWrapper.set(LabReqMain::getStateNa, value);
        if (StringUtils.isNotBlank(reqMain.getActStateCode()) && "40".equals(reqMain.getActStateCode())) {
            /*标本采集*/
            lambdaUpdateWrapper.set(LabReqMain::getIsSampling, 1);
            lambdaUpdateWrapper.set(LabReqMain::getSamplingDoctor, sysUser.getHisEmployeeCode());
            lambdaUpdateWrapper.set(LabReqMain::getSampleTypeNa, sysUser.getRealname());
            lambdaUpdateWrapper.set(LabReqMain::getSamplingTime, new Date());
        }
        if (StringUtils.isNotBlank(reqMain.getActStateCode()) && "50".equals(reqMain.getActStateCode())) {
            /*白本送出*/
        }
        if (StringUtils.isNotBlank(reqMain.getActStateCode()) && "60".equals(reqMain.getActStateCode())) {
            /*白本送达*/
        }
        if (StringUtils.isNotBlank(reqMain.getActStateCode()) && "70".equals(reqMain.getActStateCode())) {
            /*标本签收*/
            lambdaUpdateWrapper.set(LabReqMain::getIsSign, 1);
            lambdaUpdateWrapper.set(LabReqMain::getSignerDoctor, sysUser.getHisEmployeeCode());
            lambdaUpdateWrapper.set(LabReqMain::getSignerNa, sysUser.getRealname());
            lambdaUpdateWrapper.set(LabReqMain::getSignTime, new Date());
        }
        if (StringUtils.isNotBlank(reqMain.getActStateCode()) && "80".equals(reqMain.getActStateCode())) {
            /*标本退回*/
        }


        lambdaUpdateWrapper.eq(LabReqMain::getReqNo, reqMain.getReqNo());
        a = labReqMainMapper.update(reqMain, lambdaUpdateWrapper);
        String reqId = reqMain.getId();
        String reqNo = BeanUtil.isNotEmpty(reqMain) && StringUtils.isNotBlank(reqMain.getReqNo()) ? reqMain.getReqNo() : "";

        //存储当前标本状态
        LabReqState labReqState = new LabReqState();
        labReqState.setOrgId(sysUser.getOrgId());
        labReqState.setStateCode(reqMain.getActStateCode());
        labReqState.setStateValue(value);
        labReqState.setRemark(value);
        labReqState.setReqMainId(reqId);
        labReqState.setReqNo(reqNo);
        labReqState.setBatchNo(reqMain.getBatchNo());
        labReqState.setSeq(labReqStateService.getMaxCount(reqNo));
        a = labReqStateMapper.insert(labReqState);
        Result result1 = this.getReqMainByReqNo(reqMain);
        List<LabReqMain> labReqMain = (List<LabReqMain>) result1.getData();

        LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysInterface::getDelFlag, 0);
        wrapper.eq(SysInterface::getIsEnable, 1);
        wrapper.eq(SysInterface::getOrgId, reqMain.getOrgId());
        List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
        List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());
        //标本签收
        if (CollectionUtils.isNotEmpty(collect)) {
            LambdaQueryWrapper<LabReqMain> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(LabReqMain::getReqNo, reqMain.getReqNo()).eq(LabReqMain::getDelFlag, 0);
            List<LabReqMain> labReqMains = labReqMainMapper.selectList(lambdaQueryWrapper);
            for (String webUrl : collect) {
                //调用修改状态接口
                Map<String, Object> updateMap = new HashMap<>();
                updateMap.put("status", "0304");
                updateMap.put("reqNo", reqMain.getReqNo());
                updateMap.put("patType", labReqMains.get(0).getPatType());
                updateMap.put("username", sysUser.getUsername());
                updateMap.put("realname", sysUser.getRealname());
                updateMap.put("orgId", sysUser.getOrgId());
                updateMap.put("chargeType", "1");
                //标本签收
                String hl7Url = webUrl + "/public/sampleReceive";
                HttpUtil.createPost(hl7Url).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();

                String updateUrl = webUrl + "/public/updateReportStatus";
                HttpUtil.createPost(updateUrl).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();
                //调用执行医嘱确费接口
                if ("3".equals(labReqMains.get(0).getPatType())) {
                    String yzqfUrl = webUrl + "/yzqf";
                    HttpUtil.createPost(yzqfUrl).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();
//                    String updateUrlHl7 = webUrl + "/confimReceiveFee";
//                    HttpUtil.createPost(updateUrlHl7).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();
                }
            }
        }

        if (a > 0) {
            return Result.succ(1, reqMain.getBatchNo(), labReqMain);
        } else {
            return Result.fail("接收失败");
        }
    }

    @Override
    public Result findLabReqMainPageListByState(LabMaininfoPageDto maininfoPageDto) {

        Page<LabReqMain> page = new Page<LabReqMain>();
        page.setCurrent(maininfoPageDto.getPageIndex());
        page.setSize(maininfoPageDto.getPageSize());
        SysUser sysUser = RedisUserManager.getUser();
        MPJLambdaWrapper<LabReqMain> queryWrapper = new MPJLambdaWrapper<>();

        //queryWrapper.selectAll(LabReqMain.class);
        //queryWrapper.selectAs("ld", LabReqdetail::getFeeCode, LabReqMain::getFeeCode);
        //queryWrapper.selectAs("ld", LabReqdetail::getFeeName, LabReqMain::getFeeName);
        //queryWrapper.selectAs("ld", LabReqdetail::getHisReqId, LabReqMain::getHisReqId);
        // queryWrapper.leftJoin(LabReqdetail.class, "ld", LabReqdetail::getReqNo, LabReqMain::getReqNo);
        queryWrapper.eq(LabReqMain::getDelFlag, 0).in(LabReqMain::getState, maininfoPageDto.getState());
        if (ToolsUtils.isNotEmpty(maininfoPageDto.getOrgId())) {
            queryWrapper.eq(SysEventLog::getOrgId, sysUser.getOrgId());
        }
        if (ToolsUtils.isNotEmpty(maininfoPageDto.getReqNo())) {
            queryWrapper.eq(LabReqMain::getReqNo, maininfoPageDto.getReqNo());
        }
        if (ToolsUtils.isNotEmpty(maininfoPageDto.getPatId())) {
            queryWrapper.eq(LabReqMain::getPatId, maininfoPageDto.getPatId());
        }
        if (ToolsUtils.isNotEmpty(maininfoPageDto.getPatNa())) {
            queryWrapper.eq(LabReqMain::getPatNa, maininfoPageDto.getPatNa());
        }
        if (ToolsUtils.isNotEmpty(maininfoPageDto.getSamplingTimeS()) && ToolsUtils.isNotEmpty(maininfoPageDto.getSamplingTimeE())) {
            if (StringUtils.isNotBlank(maininfoPageDto.getState()) && "40".equals(maininfoPageDto.getState())) {
                queryWrapper.ge(LabReqMain::getSamplingTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSamplingTimeS()).getTime()));
                queryWrapper.le(LabReqMain::getSamplingTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSamplingTimeE()).getTime()));
            }
            /*if (StringUtils.isNotBlank(maininfoPageDto.getState()) && "50".equals(maininfoPageDto.getState())) {
                queryWrapper.ge(LabReqMain::getSamplingTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSamplingTimeS()).getTime()));
                queryWrapper.le(LabReqMain::getSamplingTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSamplingTimeE()).getTime()));
            }
            if (StringUtils.isNotBlank(maininfoPageDto.getState()) && "60".equals(maininfoPageDto.getState())) {
                queryWrapper.ge(LabReqMain::getSamplingTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSamplingTimeS()).getTime()));
                queryWrapper.le(LabReqMain::getSamplingTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSamplingTimeE()).getTime()));
            }*/
            if (StringUtils.isNotBlank(maininfoPageDto.getState()) && "70".equals(maininfoPageDto.getState())) {
                queryWrapper.ge(LabReqMain::getSignTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSamplingTimeS()).getTime()));
                queryWrapper.le(LabReqMain::getSignTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSamplingTimeE()).getTime()));
            }
        }
        List<Map<String, Object>> sexList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("Sex").getData();
        Page<LabReqMain> reqPageList = labReqMainMapper.selectPage(page, queryWrapper);

        for (LabReqMain reqMain : (List<LabReqMain>) reqPageList.getRecords()) {
            if (StringUtils.isNotBlank(reqMain.getSex()) && org.apache.commons.collections4.CollectionUtils.isNotEmpty(sexList)) {
                sexList.stream().filter(a -> a.get("code").equals(reqMain.getSex())).findFirst().ifPresent(stringObjectMap -> reqMain.setSexNa((String) stringObjectMap.get("name")));
            }
        }

        return Result.succ(1, "查询成功", reqPageList);
    }


    @Override
    public Result barcodePrintQuery(PrintBarcodeDto dto) {
        // MPJLambdaWrapper<LabHisReq> queryWrapper = new MPJLambdaWrapper<>();
        // queryWrapper.selectAll(LabHisReq.class).eq(LabHisReq::getDelFlag, 0);

        MPJLambdaWrapper<LabReqMainQuery> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabReqMainQuery.class);

        queryWrapper.selectAs("smpt", LabSampleType::getSampleTypeName, LabReqMainQuery::getSampleTypeNa);
        queryWrapper.selectAs("dept", SysOrgDepartment::getName, LabReqMainQuery::getReqDeptNa);
        queryWrapper.selectAs("reqDoc", PubEmployee::getName, LabReqMainQuery::getReqDoctorNa);
        queryWrapper.selectAs("sampDoc", PubEmployee::getName, LabReqMainQuery::getSamplingDoctorNa);
        queryWrapper.selectAs("pros", LabProcessSet::getNodeName, LabReqMainQuery::getStateNa);


        String patNo = dto.getPatNo();
        if (!StringUtils.isEmpty(patNo)) {
            queryWrapper.eq(LabReqMainQuery::getPatNo, patNo);
        }
        String reqNo = dto.getReqNo();
        if (!StringUtils.isEmpty(reqNo)) {
            queryWrapper.eq(LabReqMainQuery::getReqNo, reqNo);
        }
        String bedNo = dto.getBedNo();
        if (!StringUtils.isEmpty(bedNo)) {
            queryWrapper.eq(LabReqMainQuery::getBedNo, bedNo);
        }
        if (ToolsUtils.isNotEmpty(dto.getPatType()) && dto.getPatType().size() > 0) {
            queryWrapper.in(LabReqMainQuery::getPatType, dto.getPatType());
        }
        List<String> deptList = dto.getDeptNo();
        if (deptList.size() > 0) {
            //2025年1月14号蔡总提需求银丰项目修改
            queryWrapper.and(p -> p.in(LabReqMainQuery::getReqDept, deptList).or().in(LabReqMainQuery::getReqWard, deptList));
//            queryWrapper.in(LabReqMainQuery::getReqDept, deptList);
        }
        String patNa = dto.getPatNa();
        if (!StringUtils.isEmpty(patNa)) {
            queryWrapper.eq(LabReqMainQuery::getPatNa, patNa);
        }
        String idNo = dto.getIDNo();
        if (!StringUtils.isEmpty(idNo)) {
            queryWrapper.eq(LabReqMainQuery::getIdNo, idNo);
        }
        // queryWrapper
        //         .ge(LabHisReq::getReqTime, dto.getReqDateS())
        //         .le(LabHisReq::getReqTime, dto.getReqDateE());
        queryWrapper.between(LabReqMainQuery::getReqTime, dto.getReqDateS(), dto.getReqDateE());
        queryWrapper.leftJoin(LabSampleType.class, "smpt", p -> p.eq(LabSampleType::getSampleTypeCode, LabReqMainQuery::getSampleType).eq(LabSampleType::getDelFlag, 0).eq(LabSampleType::getOrgId, LabReqMainQuery::getOrgId).isNotNull(LabSampleType::getSampleTypeCode));
        queryWrapper.leftJoin(SysOrgDepartment.class, "dept", p -> p.eq(SysOrgDepartment::getCode, LabReqMainQuery::getReqDept).eq(SysOrgDepartment::getDelFlag, 0).eq(SysOrgDepartment::getOrgId, LabReqMainQuery::getOrgId).isNotNull(SysOrgDepartment::getCode));
        queryWrapper.leftJoin(PubEmployee.class, "reqDoc", p -> p.eq(PubEmployee::getCode, LabReqMainQuery::getReqDoctor).eq(PubEmployee::getDelFlag, 0).eq(PubEmployee::getOrgId, LabReqMainQuery::getOrgId).isNotNull(PubEmployee::getCode));
        queryWrapper.leftJoin(PubEmployee.class, "sampDoc", p -> p.eq(PubEmployee::getCode, LabReqMainQuery::getSamplingDoctor).eq(PubEmployee::getDelFlag, 0).eq(PubEmployee::getOrgId, LabReqMainQuery::getOrgId).isNotNull(PubEmployee::getCode));
        // StringBuffer existsSql = new StringBuffer("SELECT 1 FROM LAB_REQ_PRINT p WHERE t.ID = p.HIS_REQ_ID ");
        // queryWrapper.notExists(existsSql.toString());
        queryWrapper.leftJoin(LabProcessSet.class, "pros", p -> p.eq(LabProcessSet::getCode, LabReqMainQuery::getState).eq(LabProcessSet::getDelFlag, 0));
        List<LabReqMainQuery> labReqMainList = labReqMainQueryMapper.selectList(queryWrapper);

        List<Map<String, Object>> patTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("PATTYPE").getData();
        List<Map<String, Object>> sexList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("Sex").getData();
        List<Map<String, Object>> idTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("002").getData();
        for (LabReqMainQuery maininfo : labReqMainList) {
            if (StringUtils.isNotBlank(maininfo.getPatType()) && org.apache.commons.collections4.CollectionUtils.isNotEmpty(patTypeList)) {
                patTypeList.stream().filter(a -> a.get("code").equals(maininfo.getPatType())).findFirst().ifPresent(stringObjectMap -> maininfo.setPatTypeNa((String) stringObjectMap.get("name")));
            }
            if (StringUtils.isNotBlank(maininfo.getSex()) && org.apache.commons.collections4.CollectionUtils.isNotEmpty(sexList)) {
                sexList.stream().filter(a -> a.get("code").equals(maininfo.getSex())).findFirst().ifPresent(stringObjectMap -> maininfo.setSexNa((String) stringObjectMap.get("name")));
            }
            if (StringUtils.isNotBlank(maininfo.getIdType()) && org.apache.commons.collections4.CollectionUtils.isNotEmpty(idTypeList)) {
                idTypeList.stream().filter(a -> a.get("code").equals(maininfo.getIdType())).findFirst().ifPresent(stringObjectMap -> maininfo.setIdTypeNa((String) stringObjectMap.get("name")));
            }
        }

        //labReqMainList根据printTime倒序空的在后面


        // 对列表按 printTime 字段进行降序排序

        List<LabReqMainQuery> collect = labReqMainList.stream()
                .sorted(Comparator.comparing(LabReqMainQuery::getPrintTime, Comparator.nullsFirst(Comparator.naturalOrder())).reversed())
                .collect(Collectors.toList());

        // Comparator<LabReqMainQuery> comparing = Comparator.comparing(LabReqMainQuery::getPrintTime);
        // List<LabReqMainQuery> collect = labReqMainList.stream().sorted(comparing.reversed()).collect(Collectors.toList());

        return Result.succ(1, "查询成功", collect);
    }

    @Override
    public Result findLabReqMainList(LabReqMainDto labReqMain) {
        Page<LabReqMain> page = new Page<>();
        page.setCurrent(labReqMain.getPageIndex());
        page.setSize(labReqMain.getPageSize());

        MPJLambdaWrapper<LabReqMain> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.selectAll(LabReqMain.class);
        lambdaQueryWrapper.selectAs("req", PubEmployee::getName, LabReqMain::getReqDoctorName);
        lambdaQueryWrapper.selectAs(SysOrgDepartment::getName, LabReqMain::getReqDeptNa);
        lambdaQueryWrapper.leftJoin(PubEmployee.class, "req", p -> p.eq(PubEmployee::getCode, LabReqMain::getReqDoctor).eq(PubEmployee::getDelFlag, 0));
        lambdaQueryWrapper.leftJoin(SysOrgDepartment.class, p -> p.eq(SysOrgDepartment::getCode, LabReqMain::getReqDept).eq(SysOrgDepartment::getDelFlag, 0).eq(SysOrgDepartment::getOrgId, LabReqMain::getOrgId).isNotNull(SysOrgDepartment::getCode));
        lambdaQueryWrapper.eq(LabReqMain::getDelFlag, 0);

        if (ToolsUtils.isNotEmpty(labReqMain.getStartTime()) && ToolsUtils.isNotEmpty(labReqMain.getEndTime())) {
            if (StringUtils.isNotBlank(labReqMain.getTimeType())) {
                //1:申请时间+签收时间 2申请时间 3签收时间
                if (labReqMain.getTimeType().equals("1")) {
                    lambdaQueryWrapper.ge(LabReqMain::getSignTime, new Timestamp(DateUtil.parse(labReqMain.getStartTime()).getTime()));
                    lambdaQueryWrapper.le(LabReqMain::getSignTime, new Timestamp(DateUtil.parse(labReqMain.getEndTime()).getTime()));
                    lambdaQueryWrapper.ge(LabReqMain::getReqTime, new Timestamp(DateUtil.parse(labReqMain.getStartTime()).getTime()));
                    lambdaQueryWrapper.le(LabReqMain::getReqTime, new Timestamp(DateUtil.parse(labReqMain.getEndTime()).getTime()));
                } else if (labReqMain.getTimeType().equals("2")) {
                    lambdaQueryWrapper.ge(LabReqMain::getReqTime, new Timestamp(DateUtil.parse(labReqMain.getStartTime()).getTime()));
                    lambdaQueryWrapper.le(LabReqMain::getReqTime, new Timestamp(DateUtil.parse(labReqMain.getEndTime()).getTime()));
                } else {
                    lambdaQueryWrapper.ge(LabReqMain::getSignTime, new Timestamp(DateUtil.parse(labReqMain.getStartTime()).getTime()));
                    lambdaQueryWrapper.le(LabReqMain::getSignTime, new Timestamp(DateUtil.parse(labReqMain.getEndTime()).getTime()));
                }
            } else {
                lambdaQueryWrapper.ge(LabReqMain::getReqTime, new Timestamp(DateUtil.parse(labReqMain.getStartTime()).getTime()));
                lambdaQueryWrapper.le(LabReqMain::getReqTime, new Timestamp(DateUtil.parse(labReqMain.getEndTime()).getTime()));
            }
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getReqNo())) {
            lambdaQueryWrapper.eq(LabReqMain::getReqNo, labReqMain.getReqNo());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getState())) {
            lambdaQueryWrapper.eq(LabReqMain::getState, labReqMain.getState());
        }

        if (ToolsUtils.isNotEmpty(labReqMain.getBedNo())) {
            lambdaQueryWrapper.eq(LabReqMain::getBedNo, labReqMain.getBedNo());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getPatNo())) {
            lambdaQueryWrapper.eq(LabReqMain::getPatNo, labReqMain.getPatNo());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getPatNa())) {
            lambdaQueryWrapper.like(LabReqMain::getPatNa, labReqMain.getPatNa());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getIdNo())) {
            lambdaQueryWrapper.eq(LabReqMain::getIdNo, labReqMain.getIdNo());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getTelNo())) {
            lambdaQueryWrapper.like(LabReqMain::getTelNo, labReqMain.getTelNo());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getTestPurpose())) {
            lambdaQueryWrapper.like(LabReqMain::getTestPurpose, labReqMain.getTestPurpose());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getReqDept())) {
            lambdaQueryWrapper.eq(LabReqMain::getReqDept, labReqMain.getReqDept());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getPatType())) {
            lambdaQueryWrapper.eq(LabReqMain::getPatType, labReqMain.getPatType());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getCompanyCode())) {
            lambdaQueryWrapper.eq(LabReqMain::getInspectCompany, labReqMain.getCompanyCode());
        }
        Page<LabReqMain> list = labReqMainMapper.selectJoinPage(page, LabReqMain.class, lambdaQueryWrapper);

        List<Map<String, Object>> patTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("PATTYPE").getData();
        for (LabReqMain reqMain : (List<LabReqMain>) list.getRecords()) {
            if (StringUtils.isNotBlank(reqMain.getPatType()) && org.apache.commons.collections4.CollectionUtils.isNotEmpty(patTypeList)) {
                patTypeList.stream().filter(a -> a.get("code").equals(reqMain.getPatType())).findFirst().ifPresent(stringObjectMap -> reqMain.setPatTypeNa((String) stringObjectMap.get("name")));
            }
        }

        return Result.succ(1, "查询成功", list);
    }

    /*查询Tat申请信息*/
    @Override
    public Result findLabTatReqMainList(LabReqMainDto labReqMain) {
        MPJLambdaWrapper<LabMaininfo> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.selectAll(LabMaininfo.class);
        lambdaQueryWrapper.selectAs("rqmain", LabReqMainQuery::getBarCode, LabMaininfo::getBarCodeNo);
        lambdaQueryWrapper.eq(LabMaininfo::getDelFlag, 0);
        lambdaQueryWrapper.and(p -> p.isNotNull(LabMaininfo::getReqNo).ne(LabMaininfo::getReqNo, ""));
        if (ToolsUtils.isNotEmpty(labReqMain.getStartTime())) {
            Timestamp startTime = Timestamp.valueOf(labReqMain.getStartTime());
            //申请时间
            lambdaQueryWrapper.ge(LabMaininfo::getReqTime, startTime);
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getEndTime())) {
            Timestamp endTime = Timestamp.valueOf(labReqMain.getEndTime());
            lambdaQueryWrapper.le(LabMaininfo::getReqTime, endTime);
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getReqNo())) {
            lambdaQueryWrapper.eq(LabMaininfo::getReqNo, labReqMain.getReqNo());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getBedNo())) {
            lambdaQueryWrapper.eq(LabMaininfo::getBedNo, labReqMain.getBedNo());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getPatNo())) {
            lambdaQueryWrapper.eq(LabMaininfo::getPatNo, labReqMain.getPatNo());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getPatNa())) {
            lambdaQueryWrapper.like(LabMaininfo::getPatNa, labReqMain.getPatNa());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getIdNo())) {
            lambdaQueryWrapper.eq(LabMaininfo::getIdNo, labReqMain.getIdNo());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getTelNo())) {
            lambdaQueryWrapper.like(LabMaininfo::getTelNo, labReqMain.getTelNo());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getTestPurpose())) {
            lambdaQueryWrapper.like(LabMaininfo::getTestPurpose, labReqMain.getTestPurpose());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getReqDept())) {
            lambdaQueryWrapper.eq(LabMaininfo::getReqDept, labReqMain.getReqDept());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getPatType())) {
            lambdaQueryWrapper.eq(LabMaininfo::getPatType, labReqMain.getPatType());
        }

        lambdaQueryWrapper.leftJoin(LabReqMainQuery.class, "rqmain", p -> p.eq(LabReqMainQuery::getReqNo, LabMaininfo::getReqNo).eq(LabReqMainQuery::getDelFlag, 0).isNotNull(LabReqMainQuery::getReqNo).ne(LabReqMainQuery::getReqNo, ""));

        List<LabMaininfo> list = labMaininfoMapper.selectList(lambdaQueryWrapper);

        List<Map<String, Object>> patTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("PATTYPE").getData();
        for (LabMaininfo reqMain : list) {
            if (StringUtils.isNotBlank(reqMain.getPatType()) && org.apache.commons.collections4.CollectionUtils.isNotEmpty(patTypeList)) {
                patTypeList.stream().filter(a -> a.get("code").equals(reqMain.getPatType())).findFirst().ifPresent(stringObjectMap -> reqMain.setPatTypeNa((String) stringObjectMap.get("name")));
            }
        }

        String ids = list.stream().filter(p -> StringUtils.isNotBlank(p.getReqNo())).map(LabMaininfo::getReqNo).distinct().collect(Collectors.joining("','"));

        MPJLambdaWrapper<LabReqdetail> QueryDetailWrapper = new MPJLambdaWrapper<>();
        QueryDetailWrapper.eq(LabReqdetail::getDelFlag, 0);
        QueryDetailWrapper.exists("select 1 from LAB_REQ_MAIN reqmain where t.REQ_NO=reqmain.REQ_NO AND reqmain.DEL_FLAG=0 AND reqmain.REQ_NO in ('" + ids + "')");
        List<LabReqdetail> lstDetails = labReqdetailMapper.selectList(QueryDetailWrapper);

        MPJLambdaWrapper<LabTatNode> nodeQueryWrapper = new MPJLambdaWrapper<>();
        nodeQueryWrapper.eq(LabTatNode::getDelFlag, 0);
        nodeQueryWrapper.eq(LabTatNode::getIsEnable, 1);
        if (StringUtils.isNotBlank(labReqMain.getTatNodeNo())) {
            nodeQueryWrapper.eq(LabTatNode::getTatNodeNo, labReqMain.getTatNodeNo());
        }
        List<LabTatNode> tatNodes = labTatNodeMapper.selectList(nodeQueryWrapper);

        List<VxeColumn> columns = new ArrayList<>();
        columns.add(new VxeColumn("patTypeNa", "病人类型", 80, 1, "", true));
        columns.add(new VxeColumn("reqNo", "申请号", 80, 2, "", true));
        columns.add(new VxeColumn("stateNa", "状态", 80, 3, "", true));
        columns.add(new VxeColumn("patNo", "病历号", 80, 4, "", true));
        columns.add(new VxeColumn("patNa", "姓名", 80, 5, "", true));
        VxeColumn col1 = new VxeColumn("sex", "性别", 80, 6, "", true);
        VxeColumnSlots solt1 = new VxeColumnSlots();
        solt1.setDefault_("sex_default");
        solt1.setEdit(null);
        col1.setSlots(solt1);
        columns.add(col1);
        columns.add(new VxeColumn("age", "年龄", 80, 7, "", true));
        columns.add(new VxeColumn("sampleTypeNa", "样本类型", 80, 8, "", true));
        columns.add(new VxeColumn("reqDeptNa", "申请科室", 80, 9, "", true));
        columns.add(new VxeColumn("reqDoctorNa", "申请医生", 80, 10, "", true));

        int jj = 0;
        for (LabTatNode m : tatNodes) {
            VxeColumn itm = new VxeColumn(m.getTatNodeNo(), m.getTatNodeNa(), 100, 1000 + jj, "", true);
            VxeColumnSlots slot = new VxeColumnSlots();
            slot.setDefault_("dync_default");
            slot.setEdit(null);
            itm.setSlots(slot);
            columns.add(itm);
            jj++;
        }

        columns.add(new VxeColumn("reqTime", "申请时间", 80, 2000, "", true));
        columns.add(new VxeColumn("samplingTime", "采样时间", 80, 2001, "", true));
        columns.add(new VxeColumn("samplingDoctorNa", "采样医师", 80, 2002, "", true));
        columns.add(new VxeColumn("testTime", "送检时间", 80, 2003, "", true));
        columns.add(new VxeColumn("signTime", "签收时间", 80, 2004, "", true));
        columns.add(new VxeColumn("signerDoctorNa", "签收医生", 80, 2005, "", true));
        columns.add(new VxeColumn("testTime", "检验时间", 80, 2006, "", true));
        columns.add(new VxeColumn("testDoctorNa", "检验者", 80, 2007, "", true));
        columns.add(new VxeColumn("chkTime", "审核时间", 80, 2008, "", true));
        columns.add(new VxeColumn("chkDoctorNa", "审核者", 80, 2009, "", true));
        columns.add(new VxeColumn("printTime", "打印时间", 80, 2010, "", true));

        List<Map<String, Object>> lstArr = new ArrayList<>();

        try {
            for (LabMaininfo item : list) {
                Map<String, Object> map = new HashMap<>();

                // 获取类的所有字段
                Field[] fields = item.getClass().getDeclaredFields();
                for (Field field : fields) {
                    field.setAccessible(true);  // 设置可访问私有字段
                    map.put(field.getName(), field.get(item));  // 将字段名和值放入 Map
                }

                lstArr.add(map);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        /*计算TAT  时间*/
        try {
            int i = 0;
            for (LabMaininfo item : list) {
                for (LabTatNode m2 : tatNodes) {
                    List<LabReqdetail> curDetails = lstDetails.stream().filter(p -> StringUtils.isNotBlank(item.getReqNo()) && item.getReqNo().equals(p.getReqNo())).collect(Collectors.toList());
                    if (CollectionUtils.isNotEmpty(curDetails)) {
                        for (LabReqdetail m1 : curDetails) {
                            ValidateIsTatTipsParam param = new ValidateIsTatTipsParam();
                            param.setPatType(item.getPatType());
                            param.setReqDept(item.getReqDept());
                            param.setSampleType(item.getSampleType());
                            param.setFeeCode(m1.getFeeCode());
                            param.setNodeEnd(m2.getNodeStartNo());
                            param.setNodeStart(m2.getNodeEndNo());
                            param.setBarcodeNo(item.getBarCodeNo());//BarCodeNo 分管类别编号
                            param.setIsUrgent(item.getIsUrgent());
                            param.setRptGroup(item.getRptGroup());
                            param.setIsGetCurDateTime(false);

                            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            if ("10".equals(m2.getNodeStartNo())) {
                                param.setAnchorTime(BeanUtil.isEmpty(item.getReqTime()) ? "" : formatter.format(item.getReqTime()));
                            }
                            if ("20".equals(m2.getNodeStartNo())) {
                                param.setAnchorTime(BeanUtil.isEmpty(item.getCreateTime()) ? "" : formatter.format(m1.getCreateTime()));
                            }
                            if ("30".equals(m2.getNodeStartNo())) {
                                param.setAnchorTime(BeanUtil.isEmpty(item.getCreateTime()) ? "" : formatter.format(m1.getCreateTime()));
                            }
                            if ("40".equals(m2.getNodeStartNo())) {
                                param.setAnchorTime(BeanUtil.isEmpty(item.getReqTime()) ? "" : formatter.format(item.getReqTime()));
                            }
                            if ("50".equals(m2.getNodeStartNo())) {
                                param.setAnchorTime(BeanUtil.isEmpty(item.getSamplingTime()) ? "" : formatter.format(item.getSamplingTime()));
                            }
                            if ("60".equals(m2.getNodeStartNo())) {
                                param.setAnchorTime(BeanUtil.isEmpty(item.getSamplingTime()) ? "" : formatter.format(item.getSamplingTime()));
                            }
                            if ("70".equals(m2.getNodeStartNo())) {
                                param.setAnchorTime(BeanUtil.isEmpty(item.getSignTime()) ? "" : formatter.format(item.getSignTime()));
                            }

                        /*if ("80".equals(m2.getNodeStartNo())) {
                            param.setAnchorTime(formatter.format(item.getSignTime()));
                        }*/
                        /*if ("85".equals(m2.getNodeStartNo())) {
                            param.setAnchorTime(formatter.format(item.getTestTime()));
                        }*/
                            if ("90".equals(m2.getNodeStartNo())) {
                                param.setAnchorTime(BeanUtil.isEmpty(item.getTestTime()) ? "" : formatter.format(item.getTestTime()));
                            }

                            if ("100".equals(m2.getNodeStartNo())) {
                                param.setAnchorTime(BeanUtil.isEmpty(item.getChkTime()) ? "" : formatter.format(item.getChkTime()));
                            }
                        /*if ("105".equals(m2.getNodeStartNo())) {
                            param.setAnchorTime(formatter.format(item.getSignTime()));
                        }*/
                            if ("110".equals(m2.getNodeStartNo())) {
                                //param.setAnchorTime(formatter.format(item.getAl()));//危急值发布
                            }
                            if ("120".equals(m2.getNodeStartNo())) {
                                //param.setAnchorTime(formatter.format(item.getSignTime()));
                            }
                            if ("130".equals(m2.getNodeStartNo())) {
                                param.setAnchorTime(BeanUtil.isEmpty(item.getPrintTime()) ? "" : formatter.format(item.getPrintTime()));
                            }
                            if ("140".equals(m2.getNodeStartNo())) {
                                //param.setAnchorTime(formatter.format(item.getSignTime()));
                            }
                            if ("150".equals(m2.getNodeStartNo())) {
                                //param.setAnchorTime(formatter.format(item.getSignTime()));
                            }
                            if ("160".equals(m2.getNodeStartNo())) {
                                //param.setAnchorTime(formatter.format(item.getSignTime()));
                            }
                            if ("170".equals(m2.getNodeStartNo())) {
                                //param.setAnchorTime(formatter.format(item.getSignTime()));
                            }
                            if ("180".equals(m2.getNodeStartNo())) {
                                //param.setAnchorTime(formatter.format(item.getSignTime()));
                            }
                            if ("190".equals(m2.getNodeStartNo())) {
                                //param.setAnchorTime(formatter.format(item.getSignTime()));
                            }


                            /*锚点时间  结束时间*/
                            if ("10".equals(m2.getNodeEndNo())) {
                                param.setAnchorTimeEnd(BeanUtil.isEmpty(item.getReqTime()) ? "" : formatter.format(item.getReqTime()));
                            }
                            if ("20".equals(m2.getNodeEndNo())) {
                                param.setAnchorTimeEnd(BeanUtil.isEmpty(item.getCreateTime()) ? "" : formatter.format(m1.getCreateTime()));
                            }
                            if ("30".equals(m2.getNodeEndNo())) {
                                param.setAnchorTimeEnd(BeanUtil.isEmpty(item.getCreateTime()) ? "" : formatter.format(m1.getCreateTime()));
                            }
                            if ("40".equals(m2.getNodeEndNo())) {
                                param.setAnchorTimeEnd(BeanUtil.isEmpty(item.getReqTime()) ? "" : formatter.format(item.getReqTime()));
                            }
                            if ("50".equals(m2.getNodeEndNo())) {
                                param.setAnchorTimeEnd(BeanUtil.isEmpty(item.getSamplingTime()) ? "" : formatter.format(item.getSamplingTime()));
                            }
                            if ("60".equals(m2.getNodeEndNo())) {
                                param.setAnchorTimeEnd(BeanUtil.isEmpty(item.getSamplingTime()) ? "" : formatter.format(item.getSamplingTime()));
                            }
                            if ("70".equals(m2.getNodeEndNo())) {
                                param.setAnchorTimeEnd(BeanUtil.isEmpty(item.getSignTime()) ? "" : formatter.format(item.getSignTime()));
                            }

                        /*if ("80".equals(m2.getNodeStartNo())) {
                            param.setAnchorTime(formatter.format(item.getSignTime()));
                        }*/
                        /*if ("85".equals(m2.getNodeStartNo())) {
                            param.setAnchorTime(formatter.format(item.getTestTime()));
                        }*/
                            if ("90".equals(m2.getNodeEndNo())) {
                                param.setAnchorTimeEnd(BeanUtil.isEmpty(item.getTestTime()) ? "" : formatter.format(item.getTestTime()));
                            }

                            if ("100".equals(m2.getNodeEndNo())) {
                                param.setAnchorTimeEnd(BeanUtil.isEmpty(item.getChkTime()) ? "" : formatter.format(item.getChkTime()));
                            }
                        /*if ("105".equals(m2.getNodeStartNo())) {
                            param.setAnchorTime(formatter.format(item.getSignTime()));
                        }*/
                            if ("110".equals(m2.getNodeEndNo())) {
                                //param.setAnchorTime(formatter.format(item.getAl()));//危急值发布
                            }
                            if ("120".equals(m2.getNodeEndNo())) {
                                //param.setAnchorTime(formatter.format(item.getSignTime()));
                            }
                            if ("130".equals(m2.getNodeEndNo())) {
                                param.setAnchorTimeEnd(BeanUtil.isEmpty(item.getPrintTime()) ? "" : formatter.format(item.getPrintTime()));
                            }
                            if ("140".equals(m2.getNodeEndNo())) {
                                //param.setAnchorTime(formatter.format(item.getSignTime()));
                            }
                            if ("150".equals(m2.getNodeEndNo())) {
                                //param.setAnchorTime(formatter.format(item.getSignTime()));
                            }
                            if ("160".equals(m2.getNodeEndNo())) {
                                //param.setAnchorTime(formatter.format(item.getSignTime()));
                            }
                            if ("170".equals(m2.getNodeEndNo())) {
                                //param.setAnchorTime(formatter.format(item.getSignTime()));
                            }
                            if ("180".equals(m2.getNodeEndNo())) {
                                //param.setAnchorTime(formatter.format(item.getSignTime()));
                            }
                            if ("190".equals(m2.getNodeEndNo())) {
                                //param.setAnchorTime(formatter.format(item.getSignTime()));
                            }

                            ValidateIsTatTipsDto result = labTatGroupruleService.validateIsTatTipsAction(param);

                            if (result.getIsTip()) {
                                if (BeanUtil.isEmpty(lstArr.get(i)) || !lstArr.get(i).containsKey(m2.getNodeEndNo())) {
                                    lstArr.get(i).put(m2.getNodeEndNo(), result.getContentTip());
                                }
                            }
                        }
                    }
                }
                i++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        LabTatReqMainDto res = new LabTatReqMainDto();

        /*List<Map<String, Object>> lstArr = lstArr.stream()
                .filter(map -> map.containsKey()&&targetValue.equals(map.get("field1")))
                .collect(Collectors.toList());*/

        res.setLabReqMains(lstArr);

        res.setColumns(columns);

        return Result.succ(1, "查询成功", res);
    }

    @Override
    public Result findMainList(LabReqMainDto labReqMain) {
        MPJLambdaWrapper<LabReqMain> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.selectAll(LabReqMain.class);
        lambdaQueryWrapper.selectAs("em", SysUser::getRealname, LabReqMain::getCreatorNa);
        lambdaQueryWrapper.leftJoin(SysUser.class, "em", on -> on.eq(SysUser::getId, LabReqMain::getCreator).eq(SysUser::getDelFlag, 0));

        lambdaQueryWrapper.eq(LabReqMain::getDelFlag, 0);
        if (ToolsUtils.isNotEmpty(labReqMain.getStartTime())) {
            Timestamp startTime = Timestamp.valueOf(labReqMain.getStartTime());
            //申请时间
            lambdaQueryWrapper.ge(LabReqMain::getReqTime, startTime);
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getEndTime())) {
            Timestamp endTime = Timestamp.valueOf(labReqMain.getEndTime());
            lambdaQueryWrapper.le(LabReqMain::getReqTime, endTime);
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getReqNo())) {
            lambdaQueryWrapper.eq(LabReqMain::getReqNo, labReqMain.getReqNo());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getReqNos())) {
            String[] split = labReqMain.getReqNos().split(",");
            List<String> list = Arrays.stream(split).collect(Collectors.toList());
            lambdaQueryWrapper.in(LabReqMain::getReqNo, list);
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getBedNo())) {
            lambdaQueryWrapper.eq(LabReqMain::getBedNo, labReqMain.getBedNo());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getPatNo())) {
            lambdaQueryWrapper.eq(LabReqMain::getPatNo, labReqMain.getPatNo());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getPatNa())) {
            lambdaQueryWrapper.like(LabReqMain::getPatNa, labReqMain.getPatNa());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getIdNo())) {
            lambdaQueryWrapper.eq(LabReqMain::getIdNo, labReqMain.getIdNo());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getTelNo())) {
            lambdaQueryWrapper.like(LabReqMain::getTelNo, labReqMain.getTelNo());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getReqPurpose())) {
            lambdaQueryWrapper.like(LabReqMain::getReqPurpose, labReqMain.getReqPurpose());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getReqDept())) {
            lambdaQueryWrapper.eq(LabReqMain::getReqDept, labReqMain.getReqDept());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getPatType())) {
            lambdaQueryWrapper.eq(LabReqMain::getPatType, labReqMain.getPatType());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getCompanyCode())) {
            lambdaQueryWrapper.eq(LabReqMain::getInspectCompany, labReqMain.getCompanyCode());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getState())) {
            lambdaQueryWrapper.eq(LabReqMain::getState, labReqMain.getState());
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getSeachValue())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(LabReqMain::getPatNa, labReqMain.getSeachValue()).or().like(LabReqMain::getReqNo, labReqMain.getSeachValue()));
        }

        List<LabReqMain> list = labReqMainMapper.selectList(lambdaQueryWrapper);

        List<Map<String, Object>> patTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("PATTYPE").getData();
        for (LabReqMain reqMain : list) {
            if (StringUtils.isNotBlank(reqMain.getPatType()) && org.apache.commons.collections4.CollectionUtils.isNotEmpty(patTypeList)) {
                patTypeList.stream().filter(a -> a.get("code").equals(reqMain.getPatType())).findFirst().ifPresent(stringObjectMap -> reqMain.setPatTypeNa((String) stringObjectMap.get("name")));
            }
        }

        return Result.succ(1, "查询成功", list);
    }

    @Override
    public Result findReqMainAndDetailList(LabReqMainDto labReqMain) throws JsonProcessingException {

        SysParamParam sysp1 = new SysParamParam();
        sysp1.setParamCode("xtxxcs");
        sysp1.setField("tmcwjsjd");
        List<SysParamFieldValueDto> r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);

        MPJLambdaWrapper<LabReqMain> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.distinct();
        lambdaQueryWrapper.selectAll(LabReqMain.class);
        lambdaQueryWrapper.eq(LabReqMain::getDelFlag, 0);
        lambdaQueryWrapper.and(wrapper -> wrapper.isNull(LabReqMain::getIsSettle).or().ne(LabReqMain::getIsSettle, 1));
        if (ToolsUtils.isNotEmpty(labReqMain.getCompanyCode())) {
            lambdaQueryWrapper.eq(LabReqMain::getInspectCompany, labReqMain.getCompanyCode());
        }
        if (!r1.isEmpty()) {
            Integer integer = Integer.valueOf(r1.get(0).getValue());
            lambdaQueryWrapper.ge(LabReqMain::getState, integer);
        } else {
            lambdaQueryWrapper.ge(LabReqMain::getState, Integer.valueOf(labReqMain.getState()));
        }
        if (ToolsUtils.isNotEmpty(labReqMain.getSeachValue())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(LabReqMain::getPatNa, labReqMain.getSeachValue()).or().like(LabReqMain::getReqNo, labReqMain.getSeachValue()));
        }
        if (Objects.nonNull(labReqMain.getSTime()) && Objects.nonNull(labReqMain.getETime())) {
            lambdaQueryWrapper.between(LabReqMain::getReqTime, labReqMain.getSTime(), labReqMain.getETime());
        }

        List<LabReqMain> reqMainList = labReqMainMapper.selectList(lambdaQueryWrapper);
        if (CollectionUtils.isEmpty(reqMainList)) {
            return Result.fail("未查询到数据");
        }
        List<LabReqdetailDel> reqdetailList = new ArrayList<>();

        List<String> reqNoList = reqMainList.stream().filter(item -> StringUtils.isNotBlank(item.getReqNo())).map(LabReqMain::getReqNo).collect(Collectors.toList());
        List<LabReqdetailDel> labReqdetailDels = labReqdetailDelMapper.selectList(new LambdaQueryWrapper<LabReqdetailDel>().in(LabReqdetailDel::getReqNo, reqNoList).eq(LabReqdetailDel::getDelFlag, 0));
        Map<String, List<LabReqdetailDel>> detailMap = labReqdetailDels.stream().collect(Collectors.groupingBy(LabReqdetailDel::getFeeCode));
        Set<String> feeCodes = detailMap.keySet();
        //查询申请项目对照表
        List<LabFinanceSalesFeeitem> companyFeeitemList = labFinanceSalesFeeitemService.list(new LambdaQueryWrapper<LabFinanceSalesFeeitem>().in(LabFinanceSalesFeeitem::getFeeCode, feeCodes).eq(LabFinanceSalesFeeitem::getCompanyCode, labReqMain.getCompanyCode()).eq(LabFinanceSalesFeeitem::getSalesmanCode, labReqMain.getSalesmanCode()).eq(LabFinanceSalesFeeitem::getDelFlag, 0));
        Map<String, List<LabFinanceSalesFeeitem>> stringListMap = companyFeeitemList.stream().collect(Collectors.groupingBy(LabFinanceSalesFeeitem::getFeeCode));
        for (String feeCode : feeCodes) {
            List<LabReqdetailDel> reqdetailDels = detailMap.get(feeCode);
            List<String> reqNos = reqdetailDels.stream().filter(item -> StringUtils.isNotBlank(item.getReqNo())).map(LabReqdetailDel::getReqNo).collect(Collectors.toList());
            LabReqdetailDel labReqdetailDel = new LabReqdetailDel();
            List<LabFinanceSalesFeeitem> companyFeeitemList1 = stringListMap.get(feeCode);
            if (CollectionUtils.isNotEmpty(companyFeeitemList1)) {
                String brokerageType = companyFeeitemList1.get(0).getBrokerageType();
                Double brokerage = companyFeeitemList1.get(0).getBrokerage();
                Double brokerageCosts = companyFeeitemList1.get(0).getBrokerageCosts();
                if (StringUtils.isNotBlank(brokerageType) && Objects.nonNull(brokerage) && Objects.nonNull(brokerageCosts)) {
                    labReqdetailDel.setBrokerage(brokerage);
                    labReqdetailDel.setBrokerageType(brokerageType);
                    labReqdetailDel.setBrokerageCosts(brokerageCosts * reqdetailDels.size());
                }
            }
            labReqdetailDel.setFeeCode(feeCode);
            labReqdetailDel.setFeeName(reqdetailDels.get(0).getFeeName());
            Optional<BigDecimal> cost = reqdetailDels.stream().map(LabReqdetailDel::getCosts).filter(Objects::nonNull).reduce(BigDecimal::add);
            Optional<BigDecimal> amout = reqdetailDels.stream().map(LabReqdetailDel::getAmount).filter(Objects::nonNull).reduce(BigDecimal::add);
            BigDecimal costSum = cost.orElse(BigDecimal.ZERO);
            BigDecimal amoutSum = amout.orElse(BigDecimal.ZERO);
            labReqdetailDel.setCosts(costSum);
            labReqdetailDel.setAmount(amoutSum);
            labReqdetailDel.setPrice(reqdetailDels.get(0).getPrice());
            labReqdetailDel.setPeople(reqdetailDels.size());
            labReqdetailDel.setReqNo(String.join(",", reqNos));
            reqdetailList.add(labReqdetailDel);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("reqList", reqMainList);
        map.put("reqdetai", reqdetailList);

        return Result.succ(1, "查询成功", map);
    }

    /*微生物:计算应用方案、培养基等*/
    public Boolean CalcWkflwCultures(LabReqMain entry, LabMaininfo labMaininfo) {
        return labReqMainBacService.CalcWkflwCultures(entry, labMaininfo);
    }

    /*微生物:保存流程方案、流程方案节点、培养基*/
    public boolean saveWkflwNodesCultuMediums
    (List<BacTestWorkFlow> BacTestWorkFlowList, List<BacTestWorkFlowNode> BacTestWorkFlowNodeList, List<BacTestCultureMedium> BacTestCultureMediumList) {
        return labReqMainBacService.saveWkflwNodesCultuMediums(BacTestWorkFlowList, BacTestWorkFlowNodeList, BacTestCultureMediumList);
    }

    /*微生物:计算申请相关的申请项目*/
    public boolean CalcFeeItems(LabReqMain entry) {
        if (StringUtils.isEmpty(entry.getPurposeNo()) || StringUtils.isEmpty(entry.getSampleType())) {
            return true;
        }
        /*删除已存在的申请项目*/
        LambdaUpdateWrapper<LabReqdetail> lambdaQueryWrapperDel = new LambdaUpdateWrapper<>();
        //MPJLambdaWrapper<LabReqdetail> lambdaQueryWrapperDel = new MPJLambdaWrapper<>();
        lambdaQueryWrapperDel.eq(LabReqdetail::getDelFlag, 0);
        lambdaQueryWrapperDel.eq(LabReqdetail::getReqNo, entry.getReqNo());
        int ii = labReqdetailMapper.delete(lambdaQueryWrapperDel);//删除已存在的申请数据


        /*查询检验目的对照的申请项目*/
        MPJLambdaWrapper<BacReqPurposeFeeItem> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(BacReqPurposeFeeItem.class);
        queryWrapper.selectAs("pu", BacReqPurpose::getPurposeName, BacReqPurposeFeeItem::getPurposeName);
        queryWrapper.selectAs("sa", LabSampleType::getSampleTypeName, BacReqPurposeFeeItem::getSampleTypeName);
        queryWrapper.selectAs("fe", LabFeeItem::getFeeName, BacReqPurposeFeeItem::getFeeItemName);
        queryWrapper.leftJoin(BacReqPurpose.class, "pu", p -> p.eq(BacReqPurpose::getPurposeNo, BacReqPurposeFeeItem::getPurposeNo).eq(BacReqPurpose::getDelFlag, 0));
        queryWrapper.leftJoin(LabSampleType.class, "sa", p -> p.eq(LabSampleType::getSampleTypeCode, BacReqPurposeFeeItem::getSampleTypeCode).eq(LabSampleType::getSampleTypeCode, entry.getSampleType()).eq(LabSampleType::getDelFlag, 0));//LabSampleType::getId, BacReqPurposeFeeItem::getSampleTypeId);
        queryWrapper.leftJoin(LabFeeItem.class, "fe", p -> p.eq(LabFeeItem::getFeeCode, BacReqPurposeFeeItem::getFeeCode).eq(LabFeeItem::getDelFlag, 0));
        queryWrapper.eq(BacReqPurposeFeeItem::getDelFlag, 0);
        queryWrapper.and(p -> p.eq(BacReqPurposeFeeItem::getPurposeNo, entry.getPurposeNo())
                .eq(BacReqPurposeFeeItem::getSampleTypeCode, entry.getSampleType())
                .eq(BacReqPurposeFeeItem::getDelFlag, 0));
        queryWrapper.orderByAsc(BacReqPurposeFeeItem::getSeq);
        List<BacReqPurposeFeeItem> detailList = bacReqPurposeFeeItemMapper.selectList(queryWrapper);

        if (!detailList.isEmpty()) {
            //查询出申请项目
            //labFeeItemMapper
            //List<String> ids = detailList.stream().map(p -> p.getFeeItemId()).collect(Collectors.toList());
            List<String> nos = detailList.stream().map(p -> p.getFeeCode()).distinct().collect(Collectors.toList());
            MPJLambdaWrapper<LabFeeItem> lambdaQueryWrapper = new MPJLambdaWrapper<>();
            lambdaQueryWrapper.selectAll(LabFeeItem.class);
            lambdaQueryWrapper.eq(LabFeeItem::getDelFlag, 0);
            lambdaQueryWrapper.in(LabFeeItem::getFeeCode, nos);
            List<LabFeeItem> feeItemList = labFeeItemMapper.selectList(lambdaQueryWrapper);
            if (!feeItemList.isEmpty()) {
                for (LabFeeItem op : feeItemList) {
                    LabReqdetail mm = new LabReqdetail();
                    mm.setReqNo(entry.getReqNo());
                    mm.setFeeCode(op.getFeeCode());
                    mm.setFeeName(op.getFeeName());
                    mm.setAmount(new BigDecimal(1));
                    mm.setCosts(op.getCost());
                    mm.setPrice(op.getPrice());
                    mm.setIsCharge(1);
                    mm.setHisReqId(entry.getHisReqId());
                    //mm.setHisAdvNo(entry.getHisReqId());
                    labReqdetailMapper.insert(mm);
                }
            }
        }
        return true;
    }

    @Override
    public Result bacReqReception(LabReqMainReceptionParam input) {
        if (StringUtils.isEmpty(input.getReqNo())) {
            return Result.fail("请输入或扫描条码号");
        }
        SysUser sysUser = RedisUserManager.getUser();
        MPJLambdaWrapper<LabReqMain> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.eq(LabReqMain::getDelFlag, 0);
        queryWrapper.eq(LabReqMain::getReqNo, input.getReqNo());
        LabReqMain entry = labReqMainMapper.selectOne(queryWrapper);
        if (BeanUtil.isEmpty(entry)) {
            //TODO  没查到申请，重新调用接口（中间表）先拉取HIS  申请到Lab_ReqMain
            try {
                AddLabMaininfo labReqMain = new AddLabMaininfo();
                labReqMain.setReqNo(input.getReqNo());
                Result rsult = labMainInfoServiceBak.getApiReqMainInfo(labReqMain);
                if ("400".equals(rsult.getStatus().get("code") + "")) {
                    throw new RuntimeException(rsult.getStatus().get("msg") + "");
                }
            } catch (Exception e) {
                throw e;
            }
            entry = labMainInfoServiceBak.getLabReqMainEntity(input.getReqNo());
            if (BeanUtil.isEmpty(entry)) {
                throw new RuntimeException("未获取到申请信息！");
            }
        }

        if (ToolsUtils.isNotEmpty(entry) && Objects.equals(entry.getIsSign(), new BigDecimal(1))) {
            return Result.fail("无需重复签收！");
        }

        //修改申请表信息状态
        LambdaQueryWrapper<LabProcessSet> processSetWrapper = new LambdaQueryWrapper<>();
        processSetWrapper.eq(LabProcessSet::getDelFlag, 0);
        processSetWrapper.eq(LabProcessSet::getCode, "70");
        List<LabProcessSet> processSets = processSetMapper.selectList(processSetWrapper);

        String value = "";
        if (CollectionUtils.isNotEmpty(processSets)) {
            value = processSets.get(0).getNodeName();
        }
        entry.setState("70");
        entry.setStateNa(value);
        entry.setIsSign(new BigDecimal(1));
        entry.setSignTime(new Timestamp(System.currentTimeMillis()));
        entry.setSignerDoctor(sysUser.getUsername());
        entry.setSignerNa(sysUser.getRealname());
        labReqMainMapper.updateById(entry);

        CalcWkflwCultures(entry, null);
        //存储当前标本状态

        LabReqState labReqState = new LabReqState();
        labReqState.setOrgId(sysUser.getOrgId());
        labReqState.setStateCode("70");
        labReqState.setStateValue(value);
        labReqState.setRemark(value);
        labReqState.setReqMainId(entry.getId());
        labReqState.setReqNo(entry.getReqNo());
        labReqState.setBatchNo(entry.getBatchNo());
        labReqState.setSeq(labReqStateService.getMaxCount(input.getReqNo()));
        labReqStateMapper.insert(labReqState);

        //标本签收
        LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysInterface::getDelFlag, 0);
        wrapper.eq(SysInterface::getIsEnable, 1);
        wrapper.eq(SysInterface::getOrgId, entry.getOrgId());
        List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
        List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());
        /*卢瑟通道 不走接口、已计费的不走接口*/
        if (CollectionUtils.isNotEmpty(collect) && (ToolsUtils.isEmpty(entry.getIsManual())) && (ToolsUtils.isEmpty(entry.getIsCharge()))) {
            LambdaQueryWrapper<LabReqMain> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(LabReqMain::getReqNo, entry.getReqNo()).eq(LabReqMain::getDelFlag, 0);
            List<LabReqMain> labReqMains = labReqMainMapper.selectList(lambdaQueryWrapper);
            for (String webUrl : collect) {
                //调用修改状态接口
                Map<String, Object> updateMap = new HashMap<>();
                updateMap.put("status", "0304");
                updateMap.put("reqNo", entry.getReqNo());
                updateMap.put("patType", labReqMains.get(0).getPatType());
                updateMap.put("username", sysUser.getUsername());
                updateMap.put("realname", sysUser.getRealname());
                updateMap.put("orgId", sysUser.getOrgId());
                updateMap.put("chargeType", "1");
                //标本签收
                String hl7Url = webUrl + "/public/sampleReceive";
                HttpUtil.createPost(hl7Url).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();

                String updateUrl = webUrl + "/public/updateReportStatus";
                HttpUtil.createPost(updateUrl).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();
                //调用执行医嘱确费接口
                if ("3".equals(labReqMains.get(0).getPatType())) {
                    String yzqfUrl = webUrl + "/yzqf";
                    HttpUtil.createPost(yzqfUrl).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();
                }
                //添加系统参数判断是否需要重新获取计费信息，（东北双塔天健接口需求）2025-03-18
                /*添加系统参数判断是否需要重新获取计费信息*/
                SysParamParam sysp111 = new SysParamParam();
                sysp111.setParamCode("xtxxcs");
                sysp111.setField("smsjsfxycxlqsq");
                List<SysParamFieldValueDto> xtcs1 = null;
                try {
                    xtcs1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp111);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
                if (!xtcs1.isEmpty()) {
                    if (xtcs1.get(0).getValue().equals("1")) {
                        Map<String, Object> updateMap222 = new HashMap<>();
                        updateMap222.put("reqNo", entry.getReqNo());
                        updateMap222.put("username", sysUser.getUsername());
                        updateMap222.put("realname", sysUser.getRealname());
                        updateMap222.put("orgId", sysUser.getOrgId());
                        String addFeeUrl = webUrl + "/public/beginCheckAddFee";
                        String body = HttpUtil.createPost(addFeeUrl).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();
                        JSONObject jsonObject = new JSONObject(body);
                        JSONObject status = jsonObject.getJSONObject("status");
                        String code = status.get("code").toString();
                        if ("400".equals(code)) {
                            return Result.fail(jsonObject.getStr("data"));
                        }
                    }
                }

            }
        }
        return Result.succ(1, "签收成功", entry);
    }

    /*微生物不走签收、直接扫码上机处理检验目的*/
    @Override
    public Boolean bacCalcPurposeByScanReqNo(LabReqMain reqMain, LabMaininfo labMaininfo) {
        if (StringUtils.isNotBlank(reqMain.getPurposeNo())) {
            return true;
        }

        if (ToolsUtils.isNotEmpty(reqMain.getSampleType())) {
            MPJLambdaWrapper<LabReqdetail> queryWrapper = new MPJLambdaWrapper<>();
            queryWrapper.eq(LabReqdetail::getDelFlag, 0);
            queryWrapper.eq(LabReqdetail::getReqNo, reqMain.getReqNo());
            List<LabReqdetail> details = labReqdetailMapper.selectList(queryWrapper);
            if (CollectionUtils.isNotEmpty(details)) {
                List<String> feecodes = details.stream().map(LabReqdetail::getFeeCode).collect(Collectors.toList());
                MPJLambdaWrapper<BacReqPurposeFeeItem> purposeFeeItemWrapper = new MPJLambdaWrapper<>();
                purposeFeeItemWrapper.eq(BacReqPurposeFeeItem::getDelFlag, 0);
                purposeFeeItemWrapper.eq(BacReqPurposeFeeItem::getSampleTypeCode, reqMain.getSampleType());
                purposeFeeItemWrapper.in(BacReqPurposeFeeItem::getFeeCode, feecodes);
                List<BacReqPurposeFeeItem> purFeeVsList = bacReqPurposeFeeItemMapper.selectList(purposeFeeItemWrapper);
                if (CollectionUtils.isNotEmpty(purFeeVsList)) {
                    reqMain.setPurposeNo(purFeeVsList.get(0).getPurposeNo());
                    this.updateById(reqMain);
                }
            }
        }
        /*计算方案的使用*/
        this.CalcWkflwCultures(reqMain, labMaininfo);

        return true;
    }

    /*微生物检验采用默认方案*/
    @Override
    public Boolean bacTestUseDefaultWorkFlow(LabReqMain reqMain, LabMaininfo labMaininfo) {
        List<BacTestWorkFlow> BacTestWorkFlowList = new ArrayList<>();
        List<BacTestWorkFlowNode> BacTestWorkFlowNodeList = new ArrayList<>();
        /*2、获取检验目的默认的方案、培养基组合 及流程节点、培养基*/
        BacWorkFlow reqWorkFlowEntry = null;
        List<BacWorkFlowNode> reqWorkFlowNodeList = null;
        MPJLambdaWrapper<BacWorkFlow> bacWorkFlowWrapper = new MPJLambdaWrapper<>();
        bacWorkFlowWrapper.eq(BacWorkFlow::getDelFlag, 0);
        bacWorkFlowWrapper.and(p -> p.eq(BacWorkFlow::getWorkFlowCode, "mrfa").eq(BacWorkFlow::getDelFlag, 0));
        reqWorkFlowEntry = bacWorkFlowMapper.selectOne(bacWorkFlowWrapper);

        if (ToolsUtils.isEmpty(reqWorkFlowEntry)) {
            System.out.println("查不到默认方案");
            return false;
        }

        /*获取流程方案节点*/
        MPJLambdaWrapper<BacWorkFlowNode> bacWorkFlowNodeWrapper = new MPJLambdaWrapper<>();
        bacWorkFlowNodeWrapper.eq(BacWorkFlowNode::getDelFlag, 0);
        bacWorkFlowNodeWrapper.eq(BacWorkFlowNode::getFlowNo, reqWorkFlowEntry.getWorkFlowCode());
        bacWorkFlowNodeWrapper.orderByAsc(BacWorkFlowNode::getSeq);
        reqWorkFlowNodeList = bacWorkFlowNodeMapper.selectList(bacWorkFlowNodeWrapper);

        if (CollectionUtils.isEmpty(reqWorkFlowNodeList)) {
            System.out.println("查不到默认方案节点");
            return false;
        }

        String bacTestWkflwId = IdUtil.getSnowflake().nextId() + "";

        if (reqWorkFlowEntry != null && BeanUtil.isNotEmpty(reqWorkFlowEntry)) {
            BacTestWorkFlow m = new BacTestWorkFlow();
            m.setId(bacTestWkflwId);
            if (ToolsUtils.isNotEmpty(reqMain)) {
                m.setReqNo(reqMain.getReqNo());
            }
            m.setWorkFlowNo(reqWorkFlowEntry.getWorkFlowCode());
            m.setWorkFlowNa(reqWorkFlowEntry.getWorkFlowName());
            m.setSeq(1);
            //m.setCulCombinaNos(reqCultureCombinationEntry.getCode());
            if (BeanUtil.isNotEmpty(labMaininfo)) {
                m.setRptGroup(labMaininfo.getRptGroup());
                m.setSampleda(labMaininfo.getSampleda());
                m.setSampleNo(labMaininfo.getSampleNo());
            }
            BacTestWorkFlowList.add(m);
        }

        //流程方案节点
        if (!BeanUtil.isEmpty(reqWorkFlowNodeList) && !reqWorkFlowNodeList.isEmpty()) {
            for (BacWorkFlowNode m : reqWorkFlowNodeList) {
                BacTestWorkFlowNode op = new BacTestWorkFlowNode();
                op.setTestFlowNo(reqWorkFlowEntry.getWorkFlowCode());
                op.setNodeNo(m.getNodeCode());
                if (ToolsUtils.isNotEmpty(reqMain)) {
                    op.setReqNo(reqMain.getReqNo());
                }
                op.setSeq(m.getSeq());
                if (ToolsUtils.isNotEmpty(labMaininfo)) {
                    op.setRptGroup(labMaininfo.getRptGroup());
                    op.setSampleda(labMaininfo.getSampleda());
                    op.setSampleNo(labMaininfo.getSampleNo());
                }
                BacTestWorkFlowNodeList.add(op);
            }
        }

        for (BacTestWorkFlow m : BacTestWorkFlowList) {
            bacTestWorkFlowMapper.insert(m);
        }

        for (BacTestWorkFlowNode m : BacTestWorkFlowNodeList) {
            bacTestWorkFlowNodeMapper.insert(m);
        }
        //fixme:指定默认方案后给purposeNo赋值-100
        reqMain.setPurposeNo("-100");
        this.labReqMainService.updateReqMain(reqMain);
        return true;
    }

    /*微生物检验采用默认方案-默认检验目的*/
    @Override
    public Boolean bacTestUseDefaultWorkFlowWithPurpose(LabReqMain reqMain, LabMaininfo labMaininfo) {
        return labReqMainBacService.bacTestUseDefaultWorkFlowWithPurpose(reqMain, labMaininfo);
    }

    @Override
    public Boolean bacTestUpdateWorkFlow(LabReqMain reqMain, LabMaininfo labMaininfo) {
        return labReqMainBacService.bacTestUpdateWorkFlow(reqMain, labMaininfo);
    }

    /*更新方案流程三个联合主键,已走签收后扫码上机*/
    @Override
    public Boolean bacTestUpdateWorkFlowV1(LabReqMain reqMain, LabMaininfo labMaininfo) {
        return labReqMainBacService.bacTestUpdateWorkFlowV1(reqMain, labMaininfo);
    }

    @Override
    public Result addBatchReqMainAndDetail(LabReqMain reqMainParam) {
        List<LabReqMain> addReqMainList = new ArrayList<>();
        SysUser sysUser = RedisUserManager.getUser();
        List<LabReqdetailDel> labReqdetailList = reqMainParam.getLabReqdetailList();
        if (ToolsUtils.isNotEmpty(labReqdetailList)) {
            //根据remark1分组
            Map<String, List<LabReqdetailDel>> reqdetailDelMap = labReqdetailList.stream().collect(Collectors.groupingBy(LabReqdetailDel::getRemark1));
            //set集合转list集合
            List<String> keylist = new ArrayList<>(reqdetailDelMap.keySet());
            List<String> ruleCodeList = sysRuleSetService.createRuleCodeList("reqNo", keylist.size());
            for (int i = 0; i < keylist.size(); i++) {
                String reqNo = ruleCodeList.get(i);
                List<LabReqdetailDel> reqdetailDelList = reqdetailDelMap.get(keylist.get(i));
                LabReqMain addReqMain = new LabReqMain();
                //复制对象
                BeanUtil.copyProperties(reqMainParam, addReqMain, "id", "reqPurpose");
                addReqMain.setReqNo(reqNo);
                addReqMain.setBarCode(keylist.get(0));
                //取detaillist中得feeName组成逗号分隔得字符串
                addReqMain.setReqPurpose(reqdetailDelList.stream().map(LabReqdetailDel::getFeeName).collect(Collectors.joining(",")));
                int insert = labReqMainMapper.insert(addReqMain);
                if (insert > 0) {
                    //添加明细
                    addReqMainList.add(addReqMain);
                    for (LabReqdetailDel del : reqdetailDelList) {
                        del.setReqNo(addReqMain.getReqNo());
                    }
                    labReqdetailDelService.saveBatch(reqdetailDelList);
                    new Thread(() -> {
                        /*标本状态记录*/
                        LabReqState reqState = new LabReqState();
                        reqState.setReqMainId(BeanUtil.isNotEmpty(addReqMain) ? addReqMain.getId() : "");
                        reqState.setReqNo(BeanUtil.isNotEmpty(addReqMain) ? addReqMain.getReqNo() : "");
                        reqState.setStateCode(addReqMain.getState());
                        reqState.setStateValue(addReqMain.getStateNa());
                        reqState.setRemark("【" + new Timestamp(System.currentTimeMillis()) + "】,由" + sysUser.getRealname() + "," + addReqMain.getStateNa());
                        reqState.setOrgId(addReqMain.getOrgId());
                        reqState.setCreator(sysUser.getId());
                        reqState.setSeq(labReqStateService.getMaxCount(addReqMain.getReqNo()));
                        labReqStateService.save(reqState);
                    }).start();
                }
            }
        }
        return Result.succ(1, "添加成功", addReqMainList);
    }

    @Override
    public Result findReqMainAndDetail(LabReqMainDto param) {
        MPJLambdaWrapper<LabReqMain> queryWrapperr = new MPJLambdaWrapper<>();
        queryWrapperr.selectAll(LabReqMain.class);
        String reqTime = param.getReqTime();
        if (ToolsUtils.isNotEmpty(reqTime)) {
            Timestamp startTime = Timestamp.valueOf(reqTime + " 00:00:00");
            Timestamp endTime = Timestamp.valueOf(reqTime + " 23:59:59");
            queryWrapperr.ge(LabReqMain::getReqTime, startTime);
            queryWrapperr.le(LabReqMain::getReqTime, endTime);
        }
        if (ToolsUtils.isNotEmpty(param.getIsManual())) {
            queryWrapperr.eq(LabReqMain::getIsManual, param.getIsManual());
        }
        List<LabReqMain> labReqMains = labReqMainMapper.selectList(queryWrapperr);
        if (ToolsUtils.isNotEmpty(labReqMains)) {
            List<Map<String, Object>> sexList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("Sex").getData();
            List<Map<String, Object>> patTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("PATTYPE").getData();

            for (LabReqMain m : labReqMains) {
                if (ToolsUtils.isNotEmpty(m.getSex()) && ToolsUtils.isNotEmpty(sexList)) {
                    sexList.stream().filter(a -> a.get("code").equals(m.getSex())).findFirst().ifPresent(stringObjectMap -> m.setSexNa((String) stringObjectMap.get("name")));
                }

                if (ToolsUtils.isNotEmpty(m.getPatType()) && ToolsUtils.isNotEmpty(patTypeList)) {
                    patTypeList.stream().filter(a -> a.get("code").equals(m.getPatType())).findFirst().ifPresent(stringObjectMap -> m.setPatTypeNa((String) stringObjectMap.get("name")));
                }
            }

            List<String> reqNoList = labReqMains.stream().map(LabReqMain::getReqNo).collect(Collectors.toList());
            LambdaQueryWrapper<LabReqdetailDel> queryWrapperd = new LambdaQueryWrapper<>();
            queryWrapperd.eq(LabReqdetailDel::getDelFlag, 0);
            queryWrapperd.in(LabReqdetailDel::getReqNo, reqNoList);
            List<LabReqdetailDel> labReqdetailList = labReqdetailDelMapper.selectList(queryWrapperd);
            if (ToolsUtils.isNotEmpty(labReqdetailList)) {
                for (LabReqMain main : labReqMains) {
                    List<LabReqdetailDel> detailList = labReqdetailList.stream().filter(detail -> detail.getReqNo().equals(main.getReqNo())).collect(Collectors.toList());
                    main.setLabReqdetailList(detailList);
                }
            }

        }

        return Result.succ(1, "查询成功!", labReqMains);

    }

    @Override
    public Result deleteBacReqReception(LabReqMain reqMain) {
        String reqNo = reqMain.getReqNo();

        LambdaQueryWrapper<LabMaininfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LabMaininfo::getDelFlag, 0).eq(LabMaininfo::getReqNo, reqNo);
        List<LabMaininfo> labMaininfoList = labMaininfoMapper.selectList(wrapper);
        if (labMaininfoList.size() > 0) {
            return Result.fail("改条码已经上机,不允许删除!");
        }

        LambdaQueryWrapper<BacTestWorkFlow> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BacTestWorkFlow::getReqNo, reqNo).eq(BacTestWorkFlow::getDelFlag, 0);
        int delete = bacTestWorkFlowMapper.delete(queryWrapper);
        if (delete > 0) {

            LambdaQueryWrapper<BacTestWorkFlowNode> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(BacTestWorkFlowNode::getReqNo, reqNo).eq(BacTestWorkFlowNode::getDelFlag, 0);
            int delete2 = bacTestWorkFlowNodeMapper.delete(lambdaQueryWrapper);
            if (delete2 > 0) {

                LambdaQueryWrapper<BacTestCultureMedium> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(BacTestCultureMedium::getReqNo, reqNo).eq(BacTestCultureMedium::getDelFlag, 0);
                int delete1 = bacTestCultureMediumMapper.delete(queryWrapper1);
                if (delete1 > 0) {
                    reqMain.setPurposeNo("");
                    reqMain.setState("10");
                    reqMain.setStateNa("申请");
                    labReqMainMapper.updateById(reqMain);

                    SysUser sysUser = RedisUserManager.getUser();
                    LabMainState reqState1 = new LabMainState();
                    reqState1.setMaininfoId(reqMain.getId());
                    reqState1.setStateCode("10");
                    reqState1.setStateValue("申请");
                    reqState1.setRemark("由" + sysUser.getRealname() + "创建检验记录");
                    labMainStateService.save(reqState1);
                }
            }
            return Result.succ(1, "删除成功", null);
        } else {
            return Result.fail("删除失败");
        }

    }

    @Override
    public Result barcodeReprint(List<String> ids) {
        /*标本流程状态记录*/

        LambdaQueryWrapper<LabReqMain> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LabReqMain::getDelFlag, 0);
        queryWrapper.in(LabReqMain::getId, ids);
        List<LabReqMain> labReqMainList = labReqMainMapper.selectList(queryWrapper);

        //修改申请表信息状态
        LambdaQueryWrapper<LabProcessSet> processSetWrapper = new LambdaQueryWrapper<>();
        processSetWrapper.eq(LabProcessSet::getDelFlag, 0);
        processSetWrapper.eq(LabProcessSet::getCode, "25");
        List<LabProcessSet> processSets = processSetMapper.selectList(processSetWrapper);

        if (processSets.size() ==0){
            return Result.fail("未获取到词典状态信息----请检查系统设置中是否配置检验状态");
        }

        String value = "";
        if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(processSets)) {
            value = processSets.get(0).getNodeName();
        }
        if (StringUtils.isEmpty(value)) {
            return Result.fail("未获取到词典状态信息----请检查系统设置中是否配置检验状态");
        }
        SysUser finalSysUser = RedisUserManager.getUser();

        String finalValue = value;
        new Thread(() -> {
            List<LabReqState> reqStates = new ArrayList<>();
            for (LabReqMain labReqMain : labReqMainList) {
                LabReqState m = new LabReqState();
                m.setReqMainId(labReqMain.getId());
                m.setSeq(labReqStateService.getMaxCount(labReqMain.getReqNo()));
                m.setStateCode("25");
                m.setReqNo(labReqMain.getReqNo());
                m.setStateValue(finalValue);
                m.setOrgId(labReqMain.getOrgId());
                m.setCreator(finalSysUser.getId());
                String remark = "【" + new Timestamp(System.currentTimeMillis()) + "】,重打条码";
                try {
                    if (!BeanUtil.isEmpty(finalSysUser)) {
                        remark = "【" + new Timestamp(System.currentTimeMillis()) + "】,由" + finalSysUser.getRealname() + ",重打条码";
                    } else {
                        remark = "【" + new Timestamp(System.currentTimeMillis()) + "】,重打条码";
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                m.setRemark(remark);
                reqStates.add(m);
            }
            labReqStateService.saveBatch(reqStates);
        }).start();
        return Result.succ(1, "重打条码", null);
    }

    @Override
    public Result bacCreateReqMain(LabReqMain reqMain) {
        String a = sysRuleSetService.createRuleCodeList("reqNo", 1).get(0);
        reqMain.setReqNo(a);

        String ageStr = "";
        if (BeanUtil.isNotEmpty(reqMain.getAge())) {
            ageStr += reqMain.getAge();
            if (StringUtils.isNotBlank(reqMain.getAgeUnit())) {
                ageStr += reqMain.getAgeUnit();
            }
        }
        reqMain.setAgeStr(ageStr);

        boolean r = this.save(reqMain);

        if (!r) {
            return Result.fail("创建申请失败");
        }

        CalcFeeItems(reqMain);

        CalcWkflwCultures(reqMain, null);

        try {
            SysUser sysUser = RedisUserManager.getUser();

            //修改申请表信息状态
            LambdaQueryWrapper<LabProcessSet> processSetWrapper = new LambdaQueryWrapper<>();
            processSetWrapper.eq(LabProcessSet::getDelFlag, 0);
            processSetWrapper.eq(LabProcessSet::getCode, reqMain.getActStateCode());
            List<LabProcessSet> processSets = processSetMapper.selectList(processSetWrapper);

            String value = "";
            if (CollectionUtils.isNotEmpty(processSets)) {
                value = processSets.get(0).getNodeName();
            }
            //存储当前标本状态
            LabReqState labReqState = new LabReqState();
            labReqState.setOrgId(sysUser.getOrgId());
            labReqState.setStateCode(reqMain.getActStateCode());
            labReqState.setStateValue(value);
            labReqState.setRemark(value);
            labReqState.setReqMainId(reqMain.getId());
            labReqState.setReqNo(a);
            labReqState.setBatchNo(reqMain.getBatchNo());
            labReqState.setSeq(labReqStateService.getMaxCount(a));
            labReqStateMapper.insert(labReqState);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.succ(1, "操作成功", reqMain);
    }

    @Override
    public Result bacUpdateReqMain(LabReqMain reqMain) {
        this.updateById(reqMain);

        //CalcWkflwCultures(reqMain);

        //CalcFeeItems(reqMain);

        return Result.succ(1, "操作成功", reqMain);
    }

    @Override
    public Result bacUpdateReqMainWithReset(LabReqMain reqMain) {
        this.updateById(reqMain);

        deleteTestWorkFlowAndNodes(reqMain);

        /*删除已选用的培养基*/
        deleteTestCultureMediums(reqMain);

        /*删除已选用申请项目*/
        deleteFeeItems(reqMain);

        //重新采用流程方案、节点
        CalcWkflwCultures(reqMain, null);

        //重新计算申请项目
        CalcFeeItems(reqMain);

        return Result.succ(1, "操作成功", reqMain);
    }

    /*删除已选用方案、节点*/
    private boolean deleteTestWorkFlowAndNodes(LabReqMain reqMain) {
        LambdaQueryWrapper<BacTestWorkFlow> bacTestWorkFlowWrapper = new LambdaQueryWrapper<>();
        bacTestWorkFlowWrapper.eq(BacTestWorkFlow::getDelFlag, 0);
        bacTestWorkFlowWrapper.eq(BacTestWorkFlow::getReqNo, reqMain.getReqNo());
        List<BacTestWorkFlow> delList = bacTestWorkFlowMapper.selectList(bacTestWorkFlowWrapper);

        if (!delList.isEmpty()) {
            List<String> ids = delList.stream().map(BacTestWorkFlow::getWorkFlowNo).collect(Collectors.toList());

            /*删除已选用方案节点*/
            LambdaQueryWrapper<BacTestWorkFlowNode> bacTestWorkFlowNodeWrapper = new LambdaQueryWrapper<>();

            bacTestWorkFlowNodeWrapper.eq(BacTestWorkFlowNode::getDelFlag, 0);
            bacTestWorkFlowNodeWrapper.in(BacTestWorkFlowNode::getTestFlowNo, ids);
            bacTestWorkFlowNodeWrapper.eq(BacTestWorkFlowNode::getReqNo, reqMain.getReqNo());
            bacTestWorkFlowNodeMapper.delete(bacTestWorkFlowNodeWrapper);

            /*删除已选用方案*/
            bacTestWorkFlowMapper.delete(bacTestWorkFlowWrapper);
        }

        return true;
    }

    /*删除已选用培养基*/
    private boolean deleteTestCultureMediums(LabReqMain reqMain) {
        LambdaQueryWrapper<BacTestCultureMedium> bacTestCultureMediumWrapper = new LambdaQueryWrapper<>();
        bacTestCultureMediumWrapper.eq(BacTestCultureMedium::getDelFlag, 0);
        bacTestCultureMediumWrapper.eq(BacTestCultureMedium::getReqNo, reqMain.getReqNo());
        bacTestCultureMediumMapper.delete(bacTestCultureMediumWrapper);
        return true;
    }

    /*删除已有申请项目*/
    private boolean deleteFeeItems(LabReqMain reqMain) {
        LambdaQueryWrapper<LabReqdetail> lambdaQueryWrapperDel = new LambdaQueryWrapper<>();
        lambdaQueryWrapperDel.eq(LabReqdetail::getDelFlag, 0);
        lambdaQueryWrapperDel.eq(LabReqdetail::getReqNo, reqMain.getReqNo());
        labReqdetailMapper.delete(lambdaQueryWrapperDel);//删除已存在的申请数据
        return true;
    }

    /*微生物签收:获取申请列表*/
    @Override
    public Result findLabReqMainListForBacReception(LabReqMainReceptionParam input) {
        if (ToolsUtils.isEmpty(input)) {
            return Result.fail("入参不可为空");
        }
        if (ToolsUtils.isEmpty(input.getRecepDate())) {
            List<LabReqMain> arr = new ArrayList<>();
            return Result.succ(1, "成功", arr);
        }
        MPJLambdaWrapper<LabReqMain> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabReqMain.class);
        queryWrapper.selectAs("smpt", LabSampleType::getSampleTypeName, LabHisReq::getSampleTypeNa);
        queryWrapper.selectAs("dept", SysOrgDepartment::getName, LabHisReq::getReqDeptNa);
        queryWrapper.selectAs("reqDoc", PubEmployee::getName, LabHisReq::getReqDoctorNa);
        queryWrapper.selectAs("sampDoc", PubEmployee::getName, LabHisReq::getSamplingDoctorNa);
        queryWrapper.leftJoin(LabSampleType.class, "smpt", p -> p.eq(LabSampleType::getSampleTypeCode, LabReqMain::getSampleType).eq(LabSampleType::getDelFlag, 0).eq(LabSampleType::getOrgId, LabReqMain::getOrgId).isNotNull(LabSampleType::getSampleTypeCode));
        queryWrapper.leftJoin(SysOrgDepartment.class, "dept", p -> p.eq(SysOrgDepartment::getCode, LabReqMain::getReqDept).eq(SysOrgDepartment::getDelFlag, 0).eq(SysOrgDepartment::getOrgId, LabReqMain::getOrgId).isNotNull(SysOrgDepartment::getCode));
        queryWrapper.leftJoin(PubEmployee.class, "reqDoc", p -> p.eq(PubEmployee::getCode, LabReqMain::getReqDoctor).eq(PubEmployee::getDelFlag, 0).eq(PubEmployee::getOrgId, LabReqMain::getOrgId).isNotNull(PubEmployee::getCode));
        queryWrapper.leftJoin(PubEmployee.class, "sampDoc", p -> p.eq(PubEmployee::getCode, LabReqMain::getSamplingDoctor).eq(PubEmployee::getDelFlag, 0).eq(PubEmployee::getOrgId, LabReqMain::getOrgId).isNotNull(PubEmployee::getCode));
        queryWrapper.eq(LabReqMain::getDelFlag, 0);

        Timestamp startTime = Timestamp.valueOf(input.getRecepDate() + " 00:00:00");
        Timestamp endTime = Timestamp.valueOf(input.getRecepDate() + " 23:59:59");
        queryWrapper.ge(LabReqMain::getSignTime, startTime);
        queryWrapper.le(LabReqMain::getSignTime, endTime);

        if (StringUtils.isNotEmpty(input.getReqPurposeId())) {
            queryWrapper.eq(LabReqMain::getPurposeNo, input.getReqPurposeId());
        }

        DataBaseType bean = GetApplicationContext.applicationContext.getBean(DataBaseType.class);
        String dataBaseName = bean.getDataBaseName();
        if ("sqlserver".equals(dataBaseName)) {
            queryWrapper.and(p -> p.isNotNull(LabReqMain::getPurposeNo)).ne(LabReqMain::getPurposeNo, "");
        } else if ("oracle".equals(dataBaseName) || "dm".equals(dataBaseName)) {
            queryWrapper.and(p -> p.isNotNull(LabReqMain::getPurposeNo));
        }

        /*标本号范围，报告单元条件逻辑 暂未实现*/
        queryWrapper.orderByDesc(LabReqMain::getSignTime);
        List<LabReqMain> list = labReqMainMapper.selectList(queryWrapper);

        List<LabProcessSet> labProcessSetList = labProcessSetService.findProcessSetList();

        List<Map<String, Object>> patTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("PATTYPE").getData();
        List<Map<String, Object>> sexList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("Sex").getData();
        List<Map<String, Object>> idTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("002").getData();
        for (LabReqMain maininfo : list) {
            if (StringUtils.isNotBlank(maininfo.getPatType()) && org.apache.commons.collections4.CollectionUtils.isNotEmpty(patTypeList)) {
                patTypeList.stream().filter(a -> a.get("code").equals(maininfo.getPatType())).findFirst().ifPresent(stringObjectMap -> maininfo.setPatTypeNa((String) stringObjectMap.get("name")));
            }
            if (StringUtils.isNotBlank(maininfo.getSex()) && org.apache.commons.collections4.CollectionUtils.isNotEmpty(sexList)) {
                sexList.stream().filter(a -> a.get("code").equals(maininfo.getSex())).findFirst().ifPresent(stringObjectMap -> maininfo.setSexNa((String) stringObjectMap.get("name")));
            }
            if (StringUtils.isNotBlank(maininfo.getIdType()) && org.apache.commons.collections4.CollectionUtils.isNotEmpty(idTypeList)) {
                idTypeList.stream().filter(a -> a.get("code").equals(maininfo.getIdType())).findFirst().ifPresent(stringObjectMap -> maininfo.setIdTypeNa((String) stringObjectMap.get("name")));
            }
            if (StringUtils.isNotBlank(maininfo.getState()) && !labProcessSetList.isEmpty()) {
                List<LabProcessSet> tNodes = labProcessSetList.stream().filter(p -> p.getCode().equals(maininfo.getState())).collect(Collectors.toList());
                if (!tNodes.isEmpty()) {
                    maininfo.setStateNa(tNodes.get(0).getNodeName());
                }
            }
        }
        return Result.succ(1, "查询成功", list);
    }

    /*获取首选培养方案*/
    private LabReqMainSXBXDetailDto findSXWkflwAndNodesForBacReception(LabReqMainReceptionParam input) {
        LabReqMainSXBXDetailDto resDto = new LabReqMainSXBXDetailDto();
        try {
            MPJLambdaWrapper<BacReqPurpose> qRPWrapper = new MPJLambdaWrapper<>();
            qRPWrapper.eq(BacReqPurpose::getDelFlag, 0);
            qRPWrapper.eq(BacReqPurpose::getPurposeNo, input.getReqPurposeId());
            BacReqPurpose entry = bacReqPurposeMapper.selectOne(qRPWrapper);
            if (BeanUtil.isEmpty(entry)) {
                throw new Exception("微生物检验目的未配置默认方案");
            }

            resDto.setBacReqPurpose(entry);

            MPJLambdaWrapper<BacReqPurposeDetail> queryWrapper = new MPJLambdaWrapper<>();
            queryWrapper.selectAll(BacReqPurposeDetail.class);
            queryWrapper.selectAs("sa", LabSampleType::getSampleTypeName, BacReqPurposeDetail::getSampleTypeName);
            queryWrapper.eq(BacReqPurposeDetail::getDelFlag, 0);
            queryWrapper.and(p -> p.eq(BacReqPurposeDetail::getPurposeNo, input.getReqPurposeId()).eq(BacReqPurposeDetail::getDelFlag, 0));
            queryWrapper.leftJoin(LabSampleType.class, "sa", p -> p.eq(LabSampleType::getSampleTypeCode, BacReqPurposeDetail::getSampleTypeCode).eq(LabSampleType::getSampleTypeCode, input.getSampleTypeNo()).eq(LabSampleType::getDelFlag, 0));
            queryWrapper.orderByAsc(BacReqPurposeDetail::getSeq);
            List<BacReqPurposeDetail> list = bacReqPurposeDetailMapper.selectList(queryWrapper);

            if (list.isEmpty()) {
                if (StringUtils.isEmpty(entry.getCulComninaNo())) {
                    throw new Exception("微生物检验目的未配置默认培养样机组合等");
                }

                /*流程方案*/
                if (!BeanUtil.isEmpty(entry) && StringUtils.isNotEmpty(entry.getFlowNo())) {
                    MPJLambdaWrapper<BacWorkFlow> bacWorkFlowWrapper = new MPJLambdaWrapper<>();
                    bacWorkFlowWrapper.eq(BacWorkFlow::getDelFlag, 0);
                    bacWorkFlowWrapper.eq(BacWorkFlow::getWorkFlowCode, entry.getFlowNo());
                    BacWorkFlow reqWorkFlowEntry = bacWorkFlowMapper.selectOne(bacWorkFlowWrapper);
                    List<BacWorkFlow> b = new ArrayList<>();
                    b.add(reqWorkFlowEntry);
                    resDto.setBacWorkFlowList(b);

                    /*获取流程方案节点*/
                    MPJLambdaWrapper<BacWorkFlowNode> bacWorkFlowNodeWrapper = new MPJLambdaWrapper<>();
                    bacWorkFlowNodeWrapper.eq(BacWorkFlowNode::getDelFlag, 0);
                    bacWorkFlowNodeWrapper.eq(BacWorkFlowNode::getFlowNo, reqWorkFlowEntry.getWorkFlowCode());
                    bacWorkFlowNodeWrapper.orderByAsc(BacWorkFlowNode::getSeq);
                    List<BacWorkFlowNode> reqWorkFlowNodeList = bacWorkFlowNodeMapper.selectList(bacWorkFlowNodeWrapper);
                    resDto.setBacWorkFlowNodeList(reqWorkFlowNodeList);
                }

                /*培养基组合*/
                MPJLambdaWrapper<BacCultureCombination> q1 = new MPJLambdaWrapper<>();
                q1.eq(BacCultureCombination::getDelFlag, 0);
                q1.eq(BacCultureCombination::getCode, entry.getCulComninaNo());
                BacCultureCombination BCCEntry = bacCultureCombinationMapper.selectOne(q1);
                if (BeanUtil.isEmpty(BCCEntry)) {
                    throw new Exception("查无培养基信息");
                }

                List<BacCultureCombination> a = new ArrayList<>();
                a.add(BCCEntry);
                resDto.setBacCultureCombinationList(a);

                /*获取培养基组合下的培养基*/
                MPJLambdaWrapper<BacCultureCombinaRel> q2 = new MPJLambdaWrapper<>();
                q2.eq(BacCultureCombinaRel::getDelFlag, 0);
                q2.and(p -> p.eq(BacCultureCombinaRel::getCulCombinaNo, entry.getCulComninaNo()).eq(BacCultureCombinaRel::getDelFlag, 0));
                q2.selectAll(BacCultureCombinaRel.class);
                q2.selectAs("tab1", BacCultureMedium::getCode, BacCultureCombinaRel::getCultrueNo);
                q2.selectAs("tab1", BacCultureMedium::getName, BacCultureCombinaRel::getCultrueName);
                q2.leftJoin(BacCultureMedium.class, "tab1", p -> p.eq(BacCultureMedium::getCode, BacCultureCombinaRel::getCulMediumNo).eq(BacCultureMedium::getDelFlag, 0));
                List<BacCultureCombinaRel> list2 = bacCultureCombinaRelMapper.selectList(q2);

                if (list2.isEmpty()) {
                    throw new Exception("查无培养基信息");
                }

                resDto.setBacCultureCombinaRelList(list2);
                return resDto;
            }

            resDto.setBacReqPurposeDetailList(list);

            BacReqPurposeDetail ent1 = list.get(0);

            if (StringUtils.isEmpty(ent1.getSxCulCombinaNos())) {
                throw new Exception("请先维护首选方案选用培养基组合");
            }
            String[] ids = ent1.getSxCulCombinaNos().split(",");

            if (ids.length == 0) {
                throw new Exception("培养基组合数据异常");
            }

            /*流程方案*/
            if (!BeanUtil.isEmpty(ent1) && StringUtils.isNotEmpty(ent1.getSxWorkFlowNo())) {
                MPJLambdaWrapper<BacWorkFlow> bacWorkFlowWrapper = new MPJLambdaWrapper<>();
                bacWorkFlowWrapper.eq(BacWorkFlow::getDelFlag, 0);
                bacWorkFlowWrapper.eq(BacWorkFlow::getWorkFlowCode, ent1.getSxWorkFlowNo());
                BacWorkFlow reqWorkFlowEntry = bacWorkFlowMapper.selectOne(bacWorkFlowWrapper);
                List<BacWorkFlow> b = new ArrayList<>();
                b.add(reqWorkFlowEntry);
                resDto.setBacWorkFlowList(b);

                /*获取流程方案节点*/
                MPJLambdaWrapper<BacWorkFlowNode> bacWorkFlowNodeWrapper = new MPJLambdaWrapper<>();
                bacWorkFlowNodeWrapper.eq(BacWorkFlowNode::getDelFlag, 0);
                bacWorkFlowNodeWrapper.eq(BacWorkFlowNode::getFlowNo, reqWorkFlowEntry.getWorkFlowCode());
                bacWorkFlowNodeWrapper.orderByAsc(BacWorkFlowNode::getSeq);
                List<BacWorkFlowNode> reqWorkFlowNodeList = bacWorkFlowNodeMapper.selectList(bacWorkFlowNodeWrapper);
                resDto.setBacWorkFlowNodeList(reqWorkFlowNodeList);
            }

            /*获取培养基组合下的培养基*/
            MPJLambdaWrapper<BacCultureCombinaRel> q2 = new MPJLambdaWrapper<>();
            q2.eq(BacCultureCombinaRel::getDelFlag, 0);
            q2.in(BacCultureCombinaRel::getCulCombinaNo, ids);
            q2.selectAll(BacCultureCombinaRel.class);
            q2.selectAs("tab1", BacCultureMedium::getCode, BacCultureCombinaRel::getCultrueNo);
            q2.selectAs("tab1", BacCultureMedium::getName, BacCultureCombinaRel::getCultrueName);
            q2.leftJoin(BacCultureMedium.class, "tab1", p -> p.eq(BacCultureMedium::getCode, BacCultureCombinaRel::getCulMediumNo).eq(BacCultureMedium::getDelFlag, 0));
            List<BacCultureCombinaRel> list2 = bacCultureCombinaRelMapper.selectList(q2);

            if (list2.isEmpty()) {
                throw new Exception("查无培养基信息");
            }

            resDto.setBacCultureCombinaRelList(list2);
        } catch (Exception ex) {
            //TODO
        }
        return resDto;
    }

    /*获取备选培养方案*/
    private LabReqMainSXBXDetailDto findBXWkflwAndNodesForBacReception(LabReqMainReceptionParam input) {
        LabReqMainSXBXDetailDto resDto = new LabReqMainSXBXDetailDto();
        try {
            MPJLambdaWrapper<BacReqPurpose> qRPWrapper = new MPJLambdaWrapper<>();
            qRPWrapper.eq(BacReqPurpose::getDelFlag, 0);
            qRPWrapper.eq(BacReqPurpose::getId, input.getReqPurposeId());
            BacReqPurpose entry = bacReqPurposeMapper.selectOne(qRPWrapper);
            if (BeanUtil.isEmpty(entry)) {
                throw new Exception("微生物检验目的未配置默认方案");
            }

            resDto.setBacReqPurpose(entry);

            MPJLambdaWrapper<BacReqPurposeDetail> queryWrapper = new MPJLambdaWrapper<>();
            queryWrapper.selectAll(BacReqPurposeDetail.class);
            queryWrapper.selectAs("sa", LabSampleType::getSampleTypeName, BacReqPurposeDetail::getSampleTypeName);
            queryWrapper.eq(BacReqPurposeDetail::getDelFlag, 0);
            queryWrapper.eq(BacReqPurposeDetail::getPurposeNo, input.getReqPurposeId());
            queryWrapper.leftJoin(LabSampleType.class, "sa", p -> p.eq(LabSampleType::getSampleTypeCode, BacReqPurposeDetail::getSampleTypeCode).eq(LabSampleType::getSampleTypeCode, input.getSampleTypeNo()).eq(LabSampleType::getDelFlag, 0));
            queryWrapper.orderByAsc(BacReqPurposeDetail::getSeq);
            List<BacReqPurposeDetail> list = bacReqPurposeDetailMapper.selectList(queryWrapper);

            if (list.isEmpty()) {
                return resDto;
            }


            BacReqPurposeDetail ent1 = list.get(0);

            if (StringUtils.isEmpty(ent1.getBxCulCombinaNos())) {
                throw new Exception("请先维护首选方案选用培养基组合");
            }

            String[] ids = ent1.getBxCulCombinaNos().split(",");

            if (ids.length == 0) {
                throw new Exception("培养基组合数据异常");
            }

            /*备选方案*/
            MPJLambdaWrapper<BacCultureCombination> qy = new MPJLambdaWrapper<>();
            qy.eq(BacCultureCombination::getDelFlag, 0);
            qy.in(BacCultureCombination::getId, ids);
            qy.orderByAsc(BacCultureCombination::getOrderNum);
            List<BacCultureCombination> bacCultureCombinationList = bacCultureCombinationMapper.selectList(qy);
            resDto.setBacCultureCombinationList(bacCultureCombinationList);

            /*流程方案*/
            if (!BeanUtil.isEmpty(ent1) && StringUtils.isNotEmpty(ent1.getBxWorkFlowNo())) {
                MPJLambdaWrapper<BacWorkFlow> bacWorkFlowWrapper = new MPJLambdaWrapper<>();
                bacWorkFlowWrapper.eq(BacWorkFlow::getDelFlag, 0);
                bacWorkFlowWrapper.and(p -> p.eq(BacWorkFlow::getWorkFlowCode, ent1.getBxWorkFlowNo()).eq(BacWorkFlow::getDelFlag, 0));
                BacWorkFlow reqWorkFlowEntry = bacWorkFlowMapper.selectOne(bacWorkFlowWrapper);
                List<BacWorkFlow> b = new ArrayList<>();
                b.add(reqWorkFlowEntry);
                resDto.setBacWorkFlowList(b);

                /*获取流程方案节点*/
                MPJLambdaWrapper<BacWorkFlowNode> bacWorkFlowNodeWrapper = new MPJLambdaWrapper<>();
                bacWorkFlowNodeWrapper.eq(BacWorkFlowNode::getDelFlag, 0);
                bacWorkFlowNodeWrapper.eq(BacWorkFlowNode::getFlowNo, reqWorkFlowEntry.getWorkFlowCode());
                bacWorkFlowNodeWrapper.orderByAsc(BacWorkFlowNode::getSeq);
                List<BacWorkFlowNode> reqWorkFlowNodeList = bacWorkFlowNodeMapper.selectList(bacWorkFlowNodeWrapper);
                resDto.setBacWorkFlowNodeList(reqWorkFlowNodeList);
            }

            /*获取培养基组合下的培养基*/
            MPJLambdaWrapper<BacCultureCombinaRel> q2 = new MPJLambdaWrapper<>();
            q2.eq(BacCultureCombinaRel::getDelFlag, 0);
            q2.in(BacCultureCombinaRel::getCulCombinaNo, ids);
            q2.selectAll(BacCultureCombinaRel.class);
            q2.selectAs("tab1", BacCultureMedium::getCode, BacCultureCombinaRel::getCultrueNo);
            q2.selectAs("tab1", BacCultureMedium::getName, BacCultureCombinaRel::getCultrueName);
            q2.leftJoin(BacCultureMedium.class, "tab1", p -> p.eq(BacCultureMedium::getId, BacCultureCombinaRel::getCulMediumNo));
            List<BacCultureCombinaRel> list2 = bacCultureCombinaRelMapper.selectList(q2);

            if (list2.isEmpty()) {
                throw new Exception("查无培养基信息");
            }
            resDto.setBacReqPurposeDetailList(list);
            resDto.setBacCultureCombinaRelList(list2);
        } catch (Exception ex) {
            //TODO
        }
        return resDto;
    }

    /*微生物签收:加载首选方案*/
    @Override
    public Result findDefaultWkflwForBacReception(LabReqMainReceptionParam input) {
        if (StringUtils.isEmpty(input.getReqPurposeId()) || StringUtils.isEmpty(input.getSampleTypeNo())) {
            return Result.fail("微生物检验目的或标本类型为空");
        }

        LabReqMainSXBXDetailDto resDto = findSXWkflwAndNodesForBacReception(input);


        if (resDto.getBacReqPurposeDetailList() == null || resDto.getBacReqPurposeDetailList().isEmpty()) {
            if (BeanUtil.isEmpty(resDto.getBacReqPurpose())) {
                return Result.fail("微生物检验目的未配置默认方案");
            }

            if (StringUtils.isEmpty(resDto.getBacReqPurpose().getCulComninaNo())) {
                return Result.fail("微生物检验目的未配置默认培养样机组合等");
            }

            if (resDto.getBacCultureCombinationList().isEmpty() || BeanUtil.isEmpty(resDto.getBacCultureCombinationList().get(0))) {
                return Result.fail("查无培养基信息");
            }

            /*获取培养基组合下的培养基*/
            if (resDto.getBacCultureCombinaRelList().isEmpty()) {
                return Result.fail("查无培养基信息");
            }

            String resStr = resDto.getBacCultureCombinationList().get(0).getName();

            String detail = "";
            for (BacCultureCombinaRel m : resDto.getBacCultureCombinaRelList()) {
                detail = detail + m.getCultrueName() + ",";
            }
            if (detail.contains(",")) {
                detail = detail.substring(0, detail.length() - 1);
            }
            resStr = resStr + "(" + detail + ")";
            return Result.succ(1, "查询成功", resStr);
        }

        BacReqPurposeDetail ent1 = resDto.getBacReqPurposeDetailList().get(0);

        if (StringUtils.isEmpty(ent1.getSxCulCombinaNos())) {
            return Result.fail("请先维护首选方案选用培养基组合");
        }

        if (resDto.getBacCultureCombinaRelList().isEmpty()) {
            return Result.fail("查无培养基信息");
        }


        String detail = "";
        for (BacCultureCombinaRel m : resDto.getBacCultureCombinaRelList()) {
            detail = detail + m.getCultrueName() + ",";
        }
        if (detail.contains(",")) {
            detail = detail.substring(0, detail.length() - 1);
        }

        return Result.succ(1, "查询成功", detail);
    }

    /*微生物签收:切换首选方案*/
    @Override
    public Result changeDefaultWkflwForBacReception(LabReqMain reqMain) {
        boolean t1 = deleteTestWorkFlowAndNodes(reqMain);
        boolean t2 = deleteTestCultureMediums(reqMain);
        LabReqMainReceptionParam p = new LabReqMainReceptionParam();
        p.setReqPurposeId(reqMain.getPurposeNo());
        p.setSampleTypeNo(reqMain.getSampleType());
        LabReqMainSXBXDetailDto resDto = findSXWkflwAndNodesForBacReception(p);

        List<BacTestWorkFlow> BacTestWorkFlowList = new ArrayList<>();
        List<BacTestWorkFlowNode> BacTestWorkFlowNodeList = new ArrayList<>();
        List<BacTestCultureMedium> BacTestCultureMediumList = new ArrayList<>();

        /*2、获取检验目的默认的方案、培养基组合 及流程节点、培养基*/
        String bacTestWkflwId = IdUtil.getSnowflake().nextId() + "";

        //流程方案
        if (!resDto.getBacWorkFlowList().isEmpty()) {
            BacWorkFlow reqWorkFlowEntry = resDto.getBacWorkFlowList().get(0);
            BacTestWorkFlow m = new BacTestWorkFlow();
            m.setId(bacTestWkflwId);
            //m.setReqMainId(reqMain.getId());
            m.setReqNo(reqMain.getReqNo());
            m.setWorkFlowNo(reqWorkFlowEntry.getWorkFlowCode());
            m.setWorkFlowNa(reqWorkFlowEntry.getWorkFlowName());
            m.setSeq(1);
            BacTestWorkFlowList.add(m);
        }

        //流程方案节点
        if (!resDto.getBacWorkFlowNodeList().isEmpty()) {
            BacWorkFlow reqWorkFlowEntry = resDto.getBacWorkFlowList().get(0);
            int icount = 1;
            for (BacWorkFlowNode m : resDto.getBacWorkFlowNodeList()) {
                BacTestWorkFlowNode op = new BacTestWorkFlowNode();
                op.setTestFlowNo(reqWorkFlowEntry.getWorkFlowCode());
                op.setNodeNo(m.getNodeCode());
                op.setReqNo(reqMain.getReqNo());
                op.setSeq(BeanUtil.isEmpty(m.getSeq()) ? icount : m.getSeq());
                BacTestWorkFlowNodeList.add(op);
                icount++;
            }
        }

        //选用的培养基
        if (!resDto.getBacCultureCombinaRelList().isEmpty()) {
            for (BacCultureCombinaRel m : resDto.getBacCultureCombinaRelList()) {
                BacTestCultureMedium op = new BacTestCultureMedium();
//                op.setReqMainId(reqMain.getId());
                op.setReqNo(reqMain.getReqNo());
//                op.setTestWorkFlowId(bacTestWkflwId);
                //op.setWorkFlowNodeId(m.getId());
                op.setTestFlowNo(bacTestWkflwId);
                String a = sysRuleSetService.createRuleCodeList("CultuBarCode", 1).get(0);
                op.setAutoNo(a);
//                op.setCultureId(m.getCulMediumNo());
                op.setCultureNo(m.getCultrueNo());
                op.setCultureNa(m.getCultrueName());
//                op.setCultureCombinId(m.getCulCombinaNo());
                op.setCultureCombinNo(m.getCombinationNo());
                op.setCultureCombinNa(m.getCombinationNa());
                op.setIsPrintLabel(0);
                op.setPrintLabelCount(0);
                //op.setWorkFlowNodeId(m.get);
                try {
                    op.setSeq(Integer.parseInt(m.getOrderNum()));
                } catch (Exception e) {
                    //TODO
                }
                BacTestCultureMediumList.add(op);
            }
        }

        boolean ressave = saveWkflwNodesCultuMediums(BacTestWorkFlowList, BacTestWorkFlowNodeList, BacTestCultureMediumList);

        return Result.succ(1, "操作成功", reqMain);
    }

    /*微生物签收:加载备选方案*/
    @Override
    public Result findSecondWkflwForBacReception(LabReqMainReceptionParam input) {
        LabReqMainSXBXDetailDto res = findBXWkflwAndNodesForBacReception(input);
        return Result.succ(1, "加载成功", res);
    }

    /*微生物签收:切换备选方案*/
    @Override
    public Result changeSecondWkflwForBacReception(LabReqMainChangeWkflwParam input) {
        boolean t1 = deleteTestWorkFlowAndNodes(input.getLabReqMain());
        boolean t2 = deleteTestCultureMediums(input.getLabReqMain());

        List<BacTestWorkFlow> BacTestWorkFlowList = new ArrayList<>();
        List<BacTestWorkFlowNode> BacTestWorkFlowNodeList = new ArrayList<>();
        List<BacTestCultureMedium> BacTestCultureMediumList = new ArrayList<>();

        /*1、获取检验目的默认的方案、培养基组合 及流程节点、培养基*/
        BacWorkFlow reqWorkFlowEntry = null;
        List<BacWorkFlowNode> reqWorkFlowNodeList = null;
        if (!input.getBacWorkFlowList().isEmpty()) {
            MPJLambdaWrapper<BacWorkFlow> bacWorkFlowWrapper = new MPJLambdaWrapper<>();
            bacWorkFlowWrapper.eq(BacWorkFlow::getDelFlag, 0);
            bacWorkFlowWrapper.eq(BacWorkFlow::getId, input.getBacWorkFlowList().get(0).getId());
            reqWorkFlowEntry = bacWorkFlowMapper.selectOne(bacWorkFlowWrapper);

            /*获取流程方案节点*/
            MPJLambdaWrapper<BacWorkFlowNode> bacWorkFlowNodeWrapper = new MPJLambdaWrapper<>();
            bacWorkFlowNodeWrapper.eq(BacWorkFlowNode::getDelFlag, 0);
            bacWorkFlowNodeWrapper.eq(BacWorkFlowNode::getFlowNo, reqWorkFlowEntry.getWorkFlowCode());
            bacWorkFlowNodeWrapper.orderByAsc(BacWorkFlowNode::getSeq);
            reqWorkFlowNodeList = bacWorkFlowNodeMapper.selectList(bacWorkFlowNodeWrapper);
        }

        /*2、获取培养基、培养基组合*/
        BacCultureCombination reqCultureCombinationEntry = null;
        List<BacCultureCombinaRel> bacCultureCombinaRelList = null;
        if (!input.getBacCultureCombinationList().isEmpty()) {
            MPJLambdaWrapper<BacCultureCombination> bacCultureCombinationWrapper = new MPJLambdaWrapper<>();
            bacCultureCombinationWrapper.eq(BacCultureCombination::getDelFlag, 0);
            bacCultureCombinationWrapper.eq(BacCultureCombination::getId, input.getBacCultureCombinationList().get(0).getId());
            reqCultureCombinationEntry = bacCultureCombinationMapper.selectOne(bacCultureCombinationWrapper);

            //bacCultureCombinaRelMapper
            MPJLambdaWrapper<BacCultureCombinaRel> BacCultureCombinaRelWrapper = new MPJLambdaWrapper<>();
            BacCultureCombinaRelWrapper.eq(BacCultureCombinaRel::getDelFlag, 0);
            BacCultureCombinaRelWrapper.eq(BacCultureCombinaRel::getCulCombinaNo, input.getBacCultureCombinationList().get(0).getId());
            BacCultureCombinaRelWrapper.selectAll(BacCultureCombinaRel.class);
            BacCultureCombinaRelWrapper.selectAs("tab1", BacCultureMedium::getCode, BacCultureCombinaRel::getCultrueNo);
            BacCultureCombinaRelWrapper.selectAs("tab1", BacCultureMedium::getName, BacCultureCombinaRel::getCultrueName);
            BacCultureCombinaRelWrapper.selectAs("tab2", BacCultureCombination::getType, BacCultureCombinaRel::getKind);
            BacCultureCombinaRelWrapper.selectAs("tab2", BacCultureCombination::getCode, BacCultureCombinaRel::getCombinationNo);
            BacCultureCombinaRelWrapper.selectAs("tab2", BacCultureCombination::getName, BacCultureCombinaRel::getCombinationNa);
            BacCultureCombinaRelWrapper.leftJoin(BacCultureMedium.class, "tab1", p -> p.eq(BacCultureMedium::getId, BacCultureCombinaRel::getCulMediumNo).eq(BacCultureMedium::getDelFlag, 0));
            BacCultureCombinaRelWrapper.leftJoin(BacCultureCombination.class, "tab2", p -> p.eq(BacCultureCombination::getId, BacCultureCombinaRel::getCulCombinaNo).eq(BacCultureCombination::getDelFlag, 0));

            bacCultureCombinaRelList = bacCultureCombinaRelMapper.selectList(BacCultureCombinaRelWrapper);
        }

        String bacTestWkflwId = IdUtil.getSnowflake().nextId() + "";

        //流程方案
        if (reqWorkFlowEntry != null && BeanUtil.isNotEmpty(reqWorkFlowEntry)) {
            BacTestWorkFlow m = new BacTestWorkFlow();
            m.setId(bacTestWkflwId);
            //m.setReqMainId(input.getLabReqMain().getId());
            m.setReqNo(input.getLabReqMain().getReqNo());
            m.setWorkFlowNo(reqWorkFlowEntry.getWorkFlowCode());
            m.setWorkFlowNa(reqWorkFlowEntry.getWorkFlowName());
            m.setSeq(1);
            BacTestWorkFlowList.add(m);
        }

        //流程方案节点
        if (!BeanUtil.isEmpty(reqWorkFlowNodeList) && !reqWorkFlowNodeList.isEmpty()) {
            for (BacWorkFlowNode m : reqWorkFlowNodeList) {
                BacTestWorkFlowNode op = new BacTestWorkFlowNode();
                op.setTestFlowNo(bacTestWkflwId);
                op.setNodeNo(m.getNodeCode());
                op.setSeq(m.getSeq());
                op.setReqNo(input.getLabReqMain().getReqNo());
                BacTestWorkFlowNodeList.add(op);
            }
        }

        //选用的培养基
        if (!BeanUtil.isEmpty(bacCultureCombinaRelList) && !bacCultureCombinaRelList.isEmpty()) {
            for (BacCultureCombinaRel m : bacCultureCombinaRelList) {
                BacTestCultureMedium op = new BacTestCultureMedium();
//                op.setReqMainId(input.getLabReqMain().getId());
                op.setReqNo(input.getLabReqMain().getReqNo());
                op.setTestFlowNo(bacTestWkflwId);
                //op.setWorkFlowNodeId(m.getId());
                String a = sysRuleSetService.createRuleCodeList("CultuBarCode", 1).get(0);
                op.setAutoNo(a);
//                op.setCultureId(m.getCulMediumNo());
                op.setCultureNo(m.getCultrueNo());
                op.setCultureNa(m.getCultrueName());
//                op.setCultureCombinId(m.getCulCombinaNo());
                op.setCultureCombinNo(m.getCombinationNo());
                op.setCultureCombinNa(m.getCombinationNa());
                op.setIsPrintLabel(0);
                op.setPrintLabelCount(0);
                //op.setWorkFlowNodeId(m.get);
                try {
                    op.setSeq(Integer.parseInt(m.getOrderNum()));
                } catch (Exception e) {
                    //TODO
                }
                BacTestCultureMediumList.add(op);
            }
        }

        boolean ressave = saveWkflwNodesCultuMediums(BacTestWorkFlowList, BacTestWorkFlowNodeList, BacTestCultureMediumList);

        return Result.succ(1, "操作成功", input.getLabReqMain());
    }

    @Override
    public Result addReqMain(LabReqMain reqMain) {
        int insert = labReqMainMapper.insert(reqMain);
        if (insert > 0) {
            SysUser sysUser = RedisUserManager.getUser();
            new Thread(() -> {
                /*标本状态记录*/
                LabReqState reqState = new LabReqState();
                reqState.setReqMainId(BeanUtil.isNotEmpty(reqMain) ? reqMain.getId() : "");
                reqState.setReqNo(BeanUtil.isNotEmpty(reqMain) ? reqMain.getReqNo() : "");
                reqState.setStateCode(reqMain.getState());
                reqState.setStateValue(reqMain.getStateNa());
                reqState.setRemark("【" + new Timestamp(System.currentTimeMillis()) + "】,由" + sysUser.getRealname() + "," + reqMain.getStateNa());
                reqState.setOrgId(reqMain.getOrgId());

                reqState.setCreator(sysUser.getId());
                reqState.setSeq(labReqStateService.getMaxCount(reqMain.getReqNo()));
                labReqStateService.save(reqState);
            }).start();

            return Result.succ(1, "添加成功", reqMain);
        } else {
            return Result.fail(400, "添加失败", "");
        }
    }

    @Override
    public Result findReqMainList(LabReqMainDto param) {
        MPJLambdaWrapper<LabReqMain> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabReqMain.class);

        queryWrapper.selectAs("lic", LabInspectCompany::getCompanyName, LabReqMain::getInspectCompanyName);

        queryWrapper.leftJoin(LabInspectCompany.class, "lic", p -> p.eq(LabInspectCompany::getCompanyCode, LabReqMain::getInspectCompany).eq(LabInspectCompany::getDelFlag, 0));

        if (ToolsUtils.isNotEmpty(param.getCompanyCode())) {
            queryWrapper.eq(LabReqMain::getInspectCompany, param.getCompanyCode());
        }

        String reqTime = param.getReqTime();
        if (ToolsUtils.isNotEmpty(reqTime)) {
            Timestamp startTime = Timestamp.valueOf(reqTime + " 00:00:00");
            Timestamp endTime = Timestamp.valueOf(reqTime + " 23:59:59");
            queryWrapper.ge(LabReqMain::getReqTime, startTime);
            queryWrapper.le(LabReqMain::getReqTime, endTime);
        }

        String reqTimeBegin = param.getReqTimeBegin();
        if (ToolsUtils.isNotEmpty(reqTimeBegin)) {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date date = dateFormat.parse(reqTimeBegin);
                Timestamp timestampBeg = new Timestamp(date.getTime());
                queryWrapper.ge(LabReqMain::getReqTime, timestampBeg);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        String reqTimeEnd = param.getReqTimeEnd();

        if (ToolsUtils.isNotEmpty(reqTimeEnd)) {
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date date = dateFormat.parse(reqTimeEnd);
                Timestamp timestampEnd = new Timestamp(date.getTime());
                queryWrapper.le(LabReqMain::getReqTime, timestampEnd);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        String reqNo = param.getReqNo();
        if (ToolsUtils.isNotEmpty(reqNo)) {
            queryWrapper.like(LabReqMain::getReqNo, reqNo);
        }
        String state = param.getState();
        if (ToolsUtils.isNotEmpty(state)) {
            queryWrapper.eq(LabReqMain::getState, state);
        }

        String states = param.getStates();
        if (ToolsUtils.isNotEmpty(states)) {
            String[] split = states.split(",");
            queryWrapper.in(LabReqMain::getState, split);

        }
        queryWrapper.eq(LabReqMain::getDelFlag, 0);


        List<LabReqMain> labReqMains = labReqMainMapper.selectList(queryWrapper);
        if (ToolsUtils.isNotEmpty(labReqMains)) {
            List<Map<String, Object>> sexList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("Sex").getData();
            List<Map<String, Object>> patTypeList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("PATTYPE").getData();

            for (LabReqMain m : labReqMains) {
                if (ToolsUtils.isNotEmpty(m.getSex()) && ToolsUtils.isNotEmpty(sexList)) {
                    sexList.stream().filter(a -> a.get("code").equals(m.getSex())).findFirst().ifPresent(stringObjectMap -> m.setSexNa((String) stringObjectMap.get("name")));
                }

                if (ToolsUtils.isNotEmpty(m.getPatType()) && ToolsUtils.isNotEmpty(patTypeList)) {
                    patTypeList.stream().filter(a -> a.get("code").equals(m.getPatType())).findFirst().ifPresent(stringObjectMap -> m.setPatTypeNa((String) stringObjectMap.get("name")));
                }
            }
        }

        return Result.succ(1, "查询成功", labReqMains);

    }

    @Override
    public Result updateReqMain(LabReqMain reqMain) {
        int updateById = labReqMainMapper.updateById(reqMain);
        if (updateById > 0) {
            return Result.succ(1, "提交成功", reqMain);
        } else {
            return Result.fail(400, "修改失败", "");
        }
    }

    @Override
    public Result deleteReqMainById(LabReqMain reqMain) {
        //删除申请表信息
        boolean b = this.removeById(reqMain.getId());
        if (b) {
            //删除申请明细信息
            LambdaQueryWrapper<LabReqdetailDel> reqWrapper = new LambdaQueryWrapper<>();
            reqWrapper.eq(LabReqdetailDel::getReqNo, reqMain.getReqNo());
            labReqdetailDelMapper.delete(reqWrapper);
            return Result.succ(1, "删除成功", null);
        } else {
            return Result.fail(400, "删除失败", "");
        }
    }

    @Override
    public Result batchReqMainApprove(LabReqMainDto dto) {
        List<LabReqMain> reqMainList = dto.getReqMainList();
        for (LabReqMain labReqMain : reqMainList) {
            labReqMain.setState("85");
            labReqMain.setStateNa("核对");
        }
        boolean b = this.updateBatchById(reqMainList);
        if (b) {
            SysUser sysUser = RedisUserManager.getUser();
            new Thread(() -> {
                List<LabReqState> addReqStateList = new ArrayList<>();
                for (LabReqMain reqMain : reqMainList) {
                    /*标本状态记录*/
                    LabReqState reqState = new LabReqState();
                    reqState.setReqMainId(BeanUtil.isNotEmpty(reqMain) ? reqMain.getId() : "");
                    reqState.setReqNo(BeanUtil.isNotEmpty(reqMain) ? reqMain.getReqNo() : "");
                    reqState.setStateCode(reqMain.getState());
                    reqState.setStateValue(reqMain.getStateNa());
                    reqState.setRemark("【" + new Timestamp(System.currentTimeMillis()) + "】,由" + sysUser.getRealname() + "," + reqMain.getStateNa());
                    reqState.setOrgId(reqMain.getOrgId());

                    reqState.setCreator(sysUser.getId());
                    reqState.setSeq(labReqStateService.getMaxCount(reqMain.getReqNo()));
                    addReqStateList.add(reqState);
                }
                labReqStateService.saveBatch(addReqStateList);

            }).start();

            return Result.succ(1, "审核成功", null);

        } else {
            return Result.fail("审核失败");

        }
    }

    @Override
    public Result cancelReqMainApprove(LabReqMainDto dto) {
        List<LabReqMain> reqMainList = dto.getReqMainList();
        for (LabReqMain labReqMain : reqMainList) {
            labReqMain.setState("10");
            labReqMain.setStateNa("申请");
        }
        boolean b = this.updateBatchById(reqMainList);
        if (b) {
            SysUser sysUser = RedisUserManager.getUser();
            new Thread(() -> {
                List<LabReqState> addReqStateList = new ArrayList<>();
                for (LabReqMain reqMain : reqMainList) {
                    /*标本状态记录*/
                    LabReqState reqState = new LabReqState();
                    reqState.setReqMainId(BeanUtil.isNotEmpty(reqMain) ? reqMain.getId() : "");
                    reqState.setReqNo(BeanUtil.isNotEmpty(reqMain) ? reqMain.getReqNo() : "");
                    reqState.setStateCode(reqMain.getState());
                    reqState.setStateValue("取消核对");
                    reqState.setRemark("【" + new Timestamp(System.currentTimeMillis()) + "】,由" + sysUser.getRealname() + "," + reqState.getStateValue());
                    reqState.setOrgId(reqMain.getOrgId());

                    reqState.setCreator(sysUser.getId());
                    reqState.setSeq(labReqStateService.getMaxCount(reqMain.getReqNo()));
                    addReqStateList.add(reqState);
                }
                labReqStateService.saveBatch(addReqStateList);

            }).start();

            return Result.succ(1, "审核成功", null);

        } else {
            return Result.fail("审核失败");

        }
    }

    @Override
    public Result updateReqMainAndDetail(LabReqMain reqMain) {
        int updateById = labReqMainMapper.updateById(reqMain);
        if (updateById > 0) {
            //先删除，再添加
            LambdaQueryWrapper<LabReqdetailDel> delPersonWrapper = new LambdaQueryWrapper<>();
            delPersonWrapper.eq(LabReqdetailDel::getReqNo, reqMain.getReqNo());
            labReqdetailDelMapper.delete(delPersonWrapper);
            List<LabReqdetailDel> labReqdetailList = reqMain.getLabReqdetailList();
            boolean b = labReqdetailDelService.saveOrUpdateBatch(labReqdetailList);

            return Result.succ(1, "修改成功", reqMain);
        } else {
            return Result.fail(400, "修改失败", "");
        }
    }

    @Override
    public Result batchReqReportPublish(LabReqMainDto dto) {
        List<LabReqMain> reqMainList = dto.getReqMainList();
        for (LabReqMain labReqMain : reqMainList) {
            labReqMain.setState("105");
            labReqMain.setStateNa("报告发布");
        }
        boolean b = this.updateBatchById(reqMainList);
        if (b) {
            SysUser sysUser = RedisUserManager.getUser();
            new Thread(() -> {
                List<LabReqState> addReqStateList = new ArrayList<>();
                for (LabReqMain reqMain : reqMainList) {
                    /*标本状态记录*/
                    LabReqState reqState = new LabReqState();
                    reqState.setReqMainId(BeanUtil.isNotEmpty(reqMain) ? reqMain.getId() : "");
                    reqState.setReqNo(BeanUtil.isNotEmpty(reqMain) ? reqMain.getReqNo() : "");
                    reqState.setStateCode(reqMain.getState());
                    reqState.setStateValue(reqMain.getStateNa());
                    reqState.setRemark("【" + new Timestamp(System.currentTimeMillis()) + "】,由" + sysUser.getRealname() + "," + reqMain.getStateNa());
                    reqState.setOrgId(reqMain.getOrgId());

                    reqState.setCreator(sysUser.getId());
                    reqState.setSeq(labReqStateService.getMaxCount(reqMain.getReqNo()));
                    addReqStateList.add(reqState);
                }
                labReqStateService.saveBatch(addReqStateList);

            }).start();
            return Result.succ(1, "发布成功", null);

        } else {
            return Result.fail("审核失败");

        }
    }

    /*验证TAT监控*/
    @Override
    public Result validateTatRules(LabReqMainValidateTatRule input) {
        LambdaQueryWrapper<LabProcessSet> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LabProcessSet::getDelFlag, 0);
        queryWrapper.eq(LabProcessSet::getIsTat, 1);
        queryWrapper.orderByAsc(LabProcessSet::getSeq);
        List<LabProcessSet> list = labProcessSetMapper.selectList(queryWrapper);

        boolean isTip = false;

        for (LabProcessSet m : list) {
            if (StringUtils.isNotBlank(m.getCode()) && Integer.parseInt(m.getCode()) < Integer.parseInt(input.getActionCode())) {
                ValidateIsTatTipsParam param = new ValidateIsTatTipsParam();
                /*申请科室*/
                if (StringUtils.isNotBlank(input.getLabReqMain().getReqDept())) {
                    param.setReqDept(input.getLabReqMain().getReqDept());
                }
                /*样本类型*/
                if (StringUtils.isNotBlank(input.getLabReqMain().getSampleType())) {
                    param.setSampleType(input.getLabReqMain().getSampleType());
                }
                /*分管类别*/
                if (StringUtils.isNotBlank(input.getLabReqMain().getBarCode())) {
                    param.setBarcodeNo(input.getLabReqMain().getBarCode());
                }
                labTatGroupruleService.validateIsTatTipsAction(new ValidateIsTatTipsParam());
            }
        }

        return null;
    }

    /*申请闭环展示*/
    @Override
    public Result findLabReqMainClosedLoopInfo(String reqNo) {
        List<TatNodeInfoDto> res = new ArrayList<>();
        /*流程节点*/
        MPJLambdaWrapper<LabProcessSet> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.eq(LabProcessSet::getDelFlag, 0);
        lambdaQueryWrapper.eq(LabProcessSet::getIsCloopShow, 1);
        lambdaQueryWrapper.orderByAsc(LabProcessSet::getSeq);
        List<LabProcessSet> prosetList = labProcessSetMapper.selectList(lambdaQueryWrapper);

        if (CollectionUtils.isEmpty(prosetList)) {
            return Result.succ(1, "成功", res);
        }

        List<String> prosets = prosetList.stream().map(LabProcessSet::getCode).collect(Collectors.toList());

        /*列成节点 状态表*/
        MPJLambdaWrapper<LabReqState> QueryReqStateWrapper = new MPJLambdaWrapper<>();
        QueryReqStateWrapper.eq(LabReqState::getDelFlag, 0);
        QueryReqStateWrapper.eq(LabReqState::getReqNo, reqNo);
        QueryReqStateWrapper.in(LabReqState::getStateCode, prosets);
        QueryReqStateWrapper.orderByAsc(LabReqState::getCreateTime);
        List<LabReqState> reqstateList = labReqStateMapper.selectList(QueryReqStateWrapper);

        for (LabProcessSet m : prosetList) {
            if (StringUtils.isBlank(m.getCode())) {
                continue;
            }
            TatNodeInfoDto item = new TatNodeInfoDto();
            item.setTitle(m.getNodeName());

            List<LabReqState> arrs = reqstateList.stream().filter(p -> m.getCode().equals(p.getStateCode())).collect(Collectors.toList());
            String remark = arrs.stream().map(LabReqState::getRemark).collect(Collectors.joining(",\n\r"));
            item.setContent(remark);
            res.add(item);
        }

        return Result.succ(1, "成功", res);
    }

    /*申请闭环展示*/
    @Override
    public Result findLabReqMainTatInfo(String reqNo) {
        List<TatNodeInfoDto> res = new ArrayList<>();
        /*流程节点*/
        MPJLambdaWrapper<LabProcessSet> lambdaQueryWrapper = new MPJLambdaWrapper<>();
        lambdaQueryWrapper.eq(LabProcessSet::getDelFlag, 0);
        lambdaQueryWrapper.eq(LabProcessSet::getIsTat, 1);
        lambdaQueryWrapper.orderByAsc(LabProcessSet::getSeq);
        List<LabProcessSet> prosetList = labProcessSetMapper.selectList(lambdaQueryWrapper);

        if (CollectionUtils.isEmpty(prosetList)) {
            return Result.succ(1, "成功", res);
        }

        List<String> prosets = prosetList.stream().map(LabProcessSet::getCode).collect(Collectors.toList());

        /*列成节点 状态表*/
        /*MPJLambdaWrapper<LabReqState> QueryReqStateWrapper = new MPJLambdaWrapper<>();
        QueryReqStateWrapper.eq(LabReqState::getDelFlag, 0);
        QueryReqStateWrapper.eq(LabReqState::getReqNo, reqNo);
        QueryReqStateWrapper.in(LabReqState::getStateCode, prosets);
        QueryReqStateWrapper.orderByAsc(LabReqState::getCreateTime);
        List<LabReqState> reqstateList = labReqStateMapper.selectList(QueryReqStateWrapper);*/

        for (LabProcessSet m : prosetList) {
            if (StringUtils.isBlank(m.getCode())) {
                continue;
            }

            TatNodeInfoDto item = new TatNodeInfoDto();
            item.setTitle(m.getNodeName());
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            item.setTimestamp(formatter.format(m.getCreateTime()));

            item.setContent("正常");
            res.add(item);
        }

        return Result.succ(1, "成功", res);
    }

    /*作废标本*/
    @Override
    public Result cancelReqMain(String reqNo) throws JsonProcessingException {
        SysUser user = RedisUserManager.getUser();

        LambdaQueryWrapper<LabReqMain> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(LabReqMain::getDelFlag, 0);
        queryWrapper.eq(LabReqMain::getReqNo, reqNo);
        List<LabReqMain> labReqMains = labReqMainMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(labReqMains)) {
            return Result.fail("该条码已作废");
        }
        LabReqMain reqMain = labReqMains.get(0);
        //走系统参数,判断哪步之后不允许作废条码
        SysParamParam sysp1 = new SysParamParam();
        sysp1.setParamCode("cyzxxtcs");
        sysp1.setField("cybblzjd");
        List<SysParamFieldValueDto> r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
        if (!r1.isEmpty() && StringUtils.isNotBlank(r1.get(0).getValue())) {
            List<String> listValue = getListValueMethod(r1.get(0).getValue());

            if (ToolsUtils.isNotEmpty(reqMain.getState()) && !listValue.contains(reqMain.getState())) {
                return Result.fail(reqMain.getStateNa() + ",不允许作废");
            }
        }
        //调用取消打印接口
        LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysInterface::getDelFlag, 0);
        wrapper.eq(SysInterface::getIsEnable, 1);
        wrapper.eq(SysInterface::getOrgId, user.getOrgId());
        List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
        List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());

        //取消打印
        if (CollectionUtils.isNotEmpty(collect)) {
            for (String webUrl : collect) {
                //调用修改状态接口
                String updateUrl = webUrl + "/CANCLE_PRINT_BARCODE";
                Map<String, Object> updateMap = new HashMap<>();
                updateMap.put("reqNo", reqNo);
                updateMap.put("username", user.getUsername());
                updateMap.put("realname", user.getRealname());
                updateMap.put("orgId", user.getOrgId());
                String update = HttpUtil.createPost(updateUrl).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();

                //银丰医院退费
                String refoundFeeUrl = webUrl + "/lisRestFul/noticeHisReFundByReqNo";
                HttpUtil.createPost(refoundFeeUrl).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(updateMap)).contentType("application/json").execute().body();

            }
        }

        //修改申请表信息状态
        LambdaQueryWrapper<LabProcessSet> processSetWrapper = new LambdaQueryWrapper<>();
        processSetWrapper.eq(LabProcessSet::getDelFlag, 0);
        processSetWrapper.eq(LabProcessSet::getCode, "150");
        List<LabProcessSet> processSets = processSetMapper.selectList(processSetWrapper);

        String value = "";
        if (CollectionUtils.isNotEmpty(processSets)) {
            value = processSets.get(0).getNodeName();
        }
        LabReqState labReqState = new LabReqState();
        LambdaQueryWrapper<LabReqState> queryStateWrapper = new LambdaQueryWrapper<>();
        queryStateWrapper.eq(LabReqState::getReqNo, reqNo).eq(LabReqState::getOrgId, user.getOrgId())
                .eq(LabReqState::getDelFlag, 0);
        List<LabReqState> listState = labReqStateMapper.selectList(queryStateWrapper);
        labReqState.setSeq((long) (listState.size() + 1));
        labReqState.setOrgId(user.getOrgId());
        labReqState.setReqNo(reqNo);
        labReqState.setStateValue(value);
        labReqState.setStateCode("150");
        labReqStateMapper.insert(labReqState);

        /*删除申请*/
        reqMain.setDelFlag(1);
        reqMain.setState("150");
        reqMain.setStateNa(value);
        int i = labReqMainMapper.updateById(reqMain);
        //解决update del_fla修改成1的问题
        labReqMainMapper.deleteById(reqMain.getId());

        /*删除申请明细*/
        LambdaQueryWrapper<LabReqdetail> queryReqDetailWrapper = new LambdaQueryWrapper();
        queryReqDetailWrapper.eq(LabReqdetail::getDelFlag, 0);
        queryReqDetailWrapper.eq(LabReqdetail::getReqNo, reqNo);
        i = labReqdetailMapper.delete(queryReqDetailWrapper);
        /*删除中间表*/
//        LambdaQueryWrapper<LabHisReq> queryHisReqWrapper = new LambdaQueryWrapper();
//        queryHisReqWrapper.eq(LabHisReq::getDelFlag, 0);
//        queryHisReqWrapper.eq(LabHisReq::getReqNo, reqNo);

        LambdaUpdateWrapper<LabHisReq> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(LabHisReq::getReqNo, reqNo).set(LabHisReq::getDelFlag, 1);
        i = labHisReqMapper.update(null, updateWrapper);

        return Result.succ(1, "操作成功", reqMain);
    }

    private List<String> getListValueMethod(String value) {
        // 去掉首尾的方括号
        String str = value.replaceAll("\\[|\\]", "");
        // 分割字符串
        String[] parts = str.split(",");
        // 创建一个列表来存储整数
        List<String> list = new ArrayList<>();
        // 遍历分割后的字符串数组，并将其转换为整数后添加到列表中
        for (String part : parts) {
            // 去掉引号
            String numStr = part.trim().replaceAll("\"", "");
            list.add(numStr);
        }
        return list;
    }

    @Override
    public Result findLabReqMainPageListBySample(LabMaininfoPageDto maininfoPageDto) {

        MPJLambdaWrapper<LabReqMain> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.selectAll(LabReqMain.class);
        queryWrapper.distinct();
        queryWrapper.selectAs(SamstoSpecboxOrderReq::getStoragePid, LabReqMain::getStoragePid);
        queryWrapper.selectAs(SamstoSpecboxOrderReq::getStorageId, LabReqMain::getStorageId);
        queryWrapper.selectAs(SamstoSpecboxOrderReq::getFridgeId, LabReqMain::getFridgeId);
        queryWrapper.selectAs(SamstoSpecboxOrderReq::getLayerId, LabReqMain::getLayerId);
        queryWrapper.selectAs(SamstoSpecboxOrderReq::getSpecboxId, LabReqMain::getSpecboxId);
        queryWrapper.selectAs(SamstoSpecboxOrderReq::getSpecboxCode, LabReqMain::getSpecboxCode);
        queryWrapper.selectAs(SamstoSpecboxOrderReq::getSpecboxOrderId, LabReqMain::getSpecboxOrderId);
        queryWrapper.selectAs(SamstoSpecboxOrderReq::getOrderNumber, LabReqMain::getOrderNumber);
        queryWrapper.selectAs(SamstoSpecboxOrderReq::getStoragePname, LabReqMain::getStoragePname);
        queryWrapper.selectAs(SamstoSpecboxOrderReq::getStorageName, LabReqMain::getStorageName);
        queryWrapper.selectAs(SamstoSpecboxOrderReq::getFridgeCode, LabReqMain::getFridgeCode);
        queryWrapper.selectAs(SamstoSpecboxOrderReq::getLayerCode, LabReqMain::getLayerCode);
        queryWrapper.selectAs(SamstoSpecboxOrderReq::getSpecboxCode, LabReqMain::getSpecboxCode);
        queryWrapper.selectAs(SamstoSpecboxOrderReq::getId, LabReqMain::getSamstoSpecboxOrderReqId);
        queryWrapper.selectAs(SamstoSpecboxOrderReq::getStatus, LabReqMain::getStatus);

        // queryWrapper.selectCollection(LabMaininfo.class,LabReqMain::getLabMaininfoList);
        // queryWrapper.selectAssociation(SamstoSpecboxOrderReq.class,LabReqMain::getSamstoSpecboxOrderReq);
        queryWrapper.leftJoin(LabMaininfo.class, LabMaininfo::getReqNo, LabMaininfo::getReqNo);
        queryWrapper.leftJoin(SamstoSpecboxOrderReq.class, p -> p.eq(LabReqMain::getReqNo, SamstoSpecboxOrderReq::getReqNo).eq(SamstoSpecboxOrderReq::getDelFlag, 0));
        queryWrapper.leftJoin(SamstoSpecboxOrder.class, p -> p.eq(SamstoSpecboxOrder::getId, SamstoSpecboxOrderReq::getSpecboxOrderId).eq(SamstoSpecboxOrder::getDelFlag, 0));

        queryWrapper.eq(LabReqMain::getDelFlag, 0).eq(LabReqMain::getIsStore, 1).ge(LabReqMain::getState, Integer.valueOf(maininfoPageDto.getState()));
        if (ToolsUtils.isNotEmpty(maininfoPageDto.getTypeStatus())) {
            if ("1".equals(maininfoPageDto.getTypeStatus())) {
                queryWrapper.and(wrapper -> wrapper.eq(SamstoSpecboxOrderReq::getStatus, 10));
            } else {
                queryWrapper.and(wrapper -> wrapper.eq(SamstoSpecboxOrderReq::getStatus, 5).or().eq(SamstoSpecboxOrderReq::getStatus, 15));
            }
        }


        if (ToolsUtils.isNotEmpty(maininfoPageDto.getReqNo())) {
            queryWrapper.eq(LabReqMain::getReqNo, maininfoPageDto.getReqNo());
        }

        if (ToolsUtils.isNotEmpty(maininfoPageDto.getPatId())) {
            queryWrapper.eq(LabReqMain::getPatId, maininfoPageDto.getPatId());
        }

        if (ToolsUtils.isNotEmpty(maininfoPageDto.getRptGroup())) {
            queryWrapper.eq(LabMaininfo::getRptGroup, maininfoPageDto.getRptGroup());
        }

        if (ToolsUtils.isNotEmpty(maininfoPageDto.getPatNa())) {
            queryWrapper.eq(LabMaininfo::getPatNa, maininfoPageDto.getPatNa());
        }

        if (ToolsUtils.isNotEmpty(maininfoPageDto.getPatNo())) {
            queryWrapper.eq(LabMaininfo::getPatNo, maininfoPageDto.getPatNo());
        }

        if (ToolsUtils.isNotEmpty(maininfoPageDto.getSamplingTimeS()) && ToolsUtils.isNotEmpty(maininfoPageDto.getSamplingTimeE())) {
            queryWrapper.ge(SamstoSpecboxOrderReq::getEnterTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSamplingTimeS()).getTime()));
            queryWrapper.le(SamstoSpecboxOrderReq::getEnterTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSamplingTimeE()).getTime()));
        }

        if (ToolsUtils.isNotEmpty(maininfoPageDto.getSampledaBegin()) && ToolsUtils.isNotEmpty(maininfoPageDto.getSampledaEnd())) {
            queryWrapper.ge(LabMaininfo::getTestTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSampledaBegin()).getTime()));
            queryWrapper.le(LabMaininfo::getTestTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSampledaEnd()).getTime()));
        }

        // queryWrapper.in(!tAimCode.isEmpty(), LabMaininfo::getSampleNo, tAimCode);
        List<LabReqMain> reqPageList = labReqMainService.list(queryWrapper);
        return Result.succ(1, "查询成功", reqPageList);

        // Page<LabReqMain> page = new Page<LabReqMain>();
        // page.setCurrent(maininfoPageDto.getPageIndex());
        // page.setSize(maininfoPageDto.getPageSize());
        // SysUser sysUser = RedisUserManager.getUser();
        // MPJLambdaWrapper<LabReqMain> queryWrapper = new MPJLambdaWrapper<>();
        //
        // //queryWrapper.selectAll(LabReqMain.class);
        // //queryWrapper.selectAs("ld", LabReqdetail::getFeeCode, LabReqMain::getFeeCode);
        // //queryWrapper.selectAs("ld", LabReqdetail::getFeeName, LabReqMain::getFeeName);
        // //queryWrapper.selectAs("ld", LabReqdetail::getHisReqId, LabReqMain::getHisReqId);
        // // queryWrapper.leftJoin(LabReqdetail.class, "ld", LabReqdetail::getReqNo, LabReqMain::getReqNo);
        // //queryWrapper.eq(LabReqMain::getDelFlag, 0).in(LabReqMain::getState, maininfoPageDto.getState());
        // if (ToolsUtils.isNotEmpty(maininfoPageDto.getOrgId())) {
        //     queryWrapper.eq(SysEventLog::getOrgId, sysUser.getOrgId());
        // }
        // if (ToolsUtils.isNotEmpty(maininfoPageDto.getReqNo())) {
        //     queryWrapper.eq(LabReqMain::getReqNo, maininfoPageDto.getReqNo());
        // }
        // if (ToolsUtils.isNotEmpty(maininfoPageDto.getPatId())) {
        //     queryWrapper.eq(LabReqMain::getPatId, maininfoPageDto.getPatId());
        // }
        // if (ToolsUtils.isNotEmpty(maininfoPageDto.getPatNa())) {
        //     queryWrapper.eq(LabReqMain::getPatNa, maininfoPageDto.getPatNa());
        // }
        // if (ToolsUtils.isNotEmpty(maininfoPageDto.getSamplingTimeS()) && ToolsUtils.isNotEmpty(maininfoPageDto.getSamplingTimeE())) {
        //     if (StringUtils.isNotBlank(maininfoPageDto.getState()) && "40".equals(maininfoPageDto.getState())) {
        //         queryWrapper.ge(LabReqMain::getSamplingTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSamplingTimeS()).getTime()));
        //         queryWrapper.le(LabReqMain::getSamplingTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSamplingTimeE()).getTime()));
        //     }
        //     /*if (StringUtils.isNotBlank(maininfoPageDto.getState()) && "50".equals(maininfoPageDto.getState())) {
        //         queryWrapper.ge(LabReqMain::getSamplingTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSamplingTimeS()).getTime()));
        //         queryWrapper.le(LabReqMain::getSamplingTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSamplingTimeE()).getTime()));
        //     }
        //     if (StringUtils.isNotBlank(maininfoPageDto.getState()) && "60".equals(maininfoPageDto.getState())) {
        //         queryWrapper.ge(LabReqMain::getSamplingTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSamplingTimeS()).getTime()));
        //         queryWrapper.le(LabReqMain::getSamplingTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSamplingTimeE()).getTime()));
        //     }*/
        //     if (StringUtils.isNotBlank(maininfoPageDto.getState()) && "70".equals(maininfoPageDto.getState())) {
        //         queryWrapper.ge(LabReqMain::getSignTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSamplingTimeS()).getTime()));
        //         queryWrapper.le(LabReqMain::getSignTime, new Timestamp(DateUtil.parse(maininfoPageDto.getSamplingTimeE()).getTime()));
        //     }
        // }
        // List<Map<String, Object>> sexList = (List<Map<String, Object>>) sysBasDictDetailService.getSysBasDictList("Sex").getData();
        // Page<LabReqMain> reqPageList = labReqMainMapper.selectPage(page, queryWrapper);
        //
        // for (LabReqMain reqMain : (List<LabReqMain>) reqPageList.getRecords()) {
        //     if (StringUtils.isNotBlank(reqMain.getSex()) && org.apache.commons.collections4.CollectionUtils.isNotEmpty(sexList)) {
        //         sexList.stream().filter(a -> a.get("code").equals(reqMain.getSex())).findFirst().ifPresent(stringObjectMap -> reqMain.setSexNa((String) stringObjectMap.get("name")));
        //     }
        // }
        //
        // return Result.succ(1, "查询成功", reqPageList);
    }

    @Override
    public Result findLabReqAdditions(String reqNo) {
        List<LabReqMain> reqMains = new ArrayList<>();
        if (StringUtils.isBlank(reqNo)) {
            return Result.succ(1, "查询成功", reqMains);
        }
        LambdaQueryWrapper<LabReqMain> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LabReqMain::getDelFlag, 0).eq(LabReqMain::getReqNo, reqNo);
        List<LabReqMain> labReqMains = labReqMainMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(labReqMains)) {
            return Result.succ(1, "查询成功", reqMains);
        }
        LambdaQueryWrapper<LabReqAdditions> reqAddititonWrapepr = new LambdaQueryWrapper<>();
        reqAddititonWrapepr.eq(LabReqAdditions::getDelFlag, 0).eq(LabReqAdditions::getReqId, labReqMains.get(0).getId());
        List<LabReqAdditions> labReqAdditions = labReqAdditionsMapper.selectList(reqAddititonWrapepr);
        List<String> reqAdditionIds = labReqAdditions.stream().map(LabReqAdditions::getAdditionReqId).distinct().collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(reqAdditionIds)) {
            reqMains = labReqMainMapper.selectBatchIds(reqAdditionIds);
        }
        return Result.succ(1, "查询成功", reqMains);
    }

    @Override
    public Result findReqMainByReqNo(String reqNo) {
        if (StringUtils.isBlank(reqNo)) {
            return Result.succ(1, "查询成功", null);
        }
        LambdaQueryWrapper<LabReqMain> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LabReqMain::getDelFlag, 0).eq(LabReqMain::getReqNo, reqNo);
        List<LabReqMain> labReqMains = labReqMainMapper.selectList(queryWrapper);
        return Result.succ(1, "查询成功", labReqMains);

    }

    @Override
    public Result addReqAdditions(LabReqAdditionsDto labReqAdditionsDto) {
        if (ObjectUtils.isNull(labReqAdditionsDto) || StringUtils.isBlank(labReqAdditionsDto.getReqNo())) {
            return Result.fail("条码号不能为空");
        }
        if (labReqAdditionsDto.getReqNo().equals(labReqAdditionsDto.getAdditionReqNo())) {
            return Result.fail("附加条码相同,无法附加");
        }
        LambdaQueryWrapper<LabReqMain> additionQueryWrapper = new LambdaQueryWrapper<>();
        additionQueryWrapper.eq(LabReqMain::getDelFlag, 0).eq(LabReqMain::getReqNo, labReqAdditionsDto.getAdditionReqNo());
        List<LabReqMain> list = this.list(additionQueryWrapper);
        LabReqMain additionReqMain = null;
        if (CollectionUtils.isNotEmpty(list)) {
            additionReqMain = list.get(0);
        }

        LambdaQueryWrapper<LabReqMain> reqQueryWrapper = new LambdaQueryWrapper<>();
        reqQueryWrapper.eq(LabReqMain::getDelFlag, 0).eq(LabReqMain::getReqNo, labReqAdditionsDto.getReqNo());
        List<LabReqMain> reqMainList = this.list(reqQueryWrapper);
        LabReqMain reqMain = null;
        if (CollectionUtils.isNotEmpty(reqMainList)) {
            reqMain = reqMainList.get(0);
        }

        if (ObjectUtils.isNull(additionReqMain) || ObjectUtils.isNull(reqMain)) {
            return Result.fail("该附加条码在申请表不存在,无法附加");
        }
        String additionInfo = (StringUtils.isNotBlank(additionReqMain.getPatNo()) ? additionReqMain.getPatNo() : "") + (StringUtils.isNotBlank(additionReqMain.getPatNa()) ? additionReqMain.getPatNa() : "") + (StringUtils.isNotBlank(additionReqMain.getSex()) ? additionReqMain.getSex() : "");
        String reqMainInfo = (StringUtils.isNotBlank(reqMain.getPatNo()) ? reqMain.getPatNo() : "") + (StringUtils.isNotBlank(reqMain.getPatNa()) ? reqMain.getPatNa() : "") + (StringUtils.isNotBlank(reqMain.getSex()) ? reqMain.getSex() : "");
        if (!additionInfo.equals(reqMainInfo)) {
            return Result.fail("病人信息不符,无法附加");
        }

        LambdaQueryWrapper<LabReqAdditions> reqAddititonWrapepr = new LambdaQueryWrapper<>();
        reqAddititonWrapepr.eq(LabReqAdditions::getDelFlag, 0).eq(LabReqAdditions::getAdditionReqId, additionReqMain.getId());
        List<LabReqAdditions> labReqAdditions = labReqAdditionsMapper.selectList(reqAddititonWrapepr);
        if (CollectionUtils.isNotEmpty(labReqAdditions)) {
            List<String> reqIds = labReqAdditions.stream().map(LabReqAdditions::getReqId).distinct().collect(Collectors.toList());
            List<LabReqMain> reqMains = this.listByIds(reqIds);
            String reqNos = reqMains.stream().map(LabReqMain::getReqNo).collect(Collectors.joining(", "));
            return Result.fail("该附加条码与条码号:(" + reqNos + ")所绑定");
        }
        LambdaQueryWrapper<LabMaininfo> reqWrapper = new LambdaQueryWrapper<>();
        reqWrapper.eq(LabMaininfo::getDelFlag, 0).eq(StringUtils.isNotBlank(labReqAdditionsDto.getRptGroup()), LabMaininfo::getRptGroup, labReqAdditionsDto.getRptGroup()).eq(LabMaininfo::getReqNo, labReqAdditionsDto.getReqNo());
        List<LabMaininfo> labMaininfos = labMaininfoMapper.selectList(reqWrapper);

        LabMaininfo labMaininfo = null;
        if (CollectionUtils.isNotEmpty(labMaininfos)) {
            labMaininfo = labMaininfos.get(0);
        }
        //已初审/已审核/已锁定状态不能进行添加
        if (ObjectUtils.isNotNull(labMaininfo.getIsChk()) && labMaininfo.getIsChk().equals(new BigDecimal(1))) {
            return Result.fail("检验主记录状态为'已初审',无法附加");
        }
        if (ObjectUtils.isNotNull(labMaininfo.getIsChk()) && labMaininfo.getIsChk().equals(new BigDecimal(2))) {
            return Result.fail("检验主记录状态为'已审核',无法附加");
        }
        if (ObjectUtils.isNotNull(labMaininfo.getIsLock()) && labMaininfo.getIsLock().equals(1)) {
            return Result.fail("检验主记录状态为'已锁定',无法附加");
        }
        LabReqAdditions saveLabReqAdditions = new LabReqAdditions();
        saveLabReqAdditions.setReqId(reqMain.getId());
        saveLabReqAdditions.setAdditionReqId(additionReqMain.getId());
        int insert = labReqAdditionsMapper.insert(saveLabReqAdditions);
        if (insert > 0) {
            //重置检验目的,获取主和附加的申请明细,动态拼接项目名称,塞入到申请和检验主记录表里
            //查询关联的附加信息
            LambdaQueryWrapper<LabReqAdditions> reqAddititonAllWrapepr = new LambdaQueryWrapper<>();
            reqAddititonAllWrapepr.eq(LabReqAdditions::getDelFlag, 0).eq(LabReqAdditions::getReqId, reqMain.getId());
            List<LabReqAdditions> labReqAdditions1 = labReqAdditionsMapper.selectList(reqAddititonAllWrapepr);
            List<String> additionIds = labReqAdditions1.stream().map(LabReqAdditions::getAdditionReqId).distinct().collect(Collectors.toList());
            additionIds.add(reqMain.getId());
            List<String> reqNos = this.listByIds(additionIds).stream().map(LabReqMain::getReqNo).distinct().collect(Collectors.toList());

            LambdaQueryWrapper<LabReqdetail> reqdetailWrapper = new LambdaQueryWrapper<>();
            reqdetailWrapper.in(LabReqdetail::getReqNo, reqNos);
            String feeName = labReqdetailMapper.selectList(reqdetailWrapper).stream().map(LabReqdetail::getFeeName).collect(Collectors.joining(", "));
            reqMain.setTestPurpose(feeName);
            labMaininfo.setTestPurpose(feeName);
            this.updateById(reqMain);
            labMaininfoMapper.updateById(labMaininfo);
            return Result.succ(1, "附加成功", saveLabReqAdditions);
        } else {
            return Result.fail("附加失败！");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result deleteReqAdditions(LabReqAdditionsDto labReqAdditionsDto) {
        if (ObjectUtils.isNull(labReqAdditionsDto)) {
            return Result.fail("取消附加信息为空！");
        }
        //删除附件中间表信息
        LambdaQueryWrapper<LabReqAdditions> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(LabReqAdditions::getAdditionReqId, labReqAdditionsDto.getId());
        LabReqAdditions labReqAdditions = labReqAdditionsMapper.selectList(wrapper).get(0);
        int rows = labReqAdditionsMapper.delete(wrapper);
        if (rows > 0) {
            //删除申请表信息
            this.removeById(labReqAdditionsDto.getId());
            //删除申请明细信息
            LambdaQueryWrapper<LabReqdetail> reqWrapper = new LambdaQueryWrapper<>();
            reqWrapper.eq(LabReqdetail::getReqNo, labReqAdditionsDto.getReqNo());
            labReqdetailMapper.delete(reqWrapper);

            //修改检验目的
            LambdaQueryWrapper<LabReqAdditions> reqAddititonAllWrapepr = new LambdaQueryWrapper<>();
            reqAddititonAllWrapepr.eq(LabReqAdditions::getDelFlag, 0).eq(LabReqAdditions::getReqId, labReqAdditions.getReqId());
            List<LabReqAdditions> labReqAdditions1 = labReqAdditionsMapper.selectList(reqAddititonAllWrapepr);
            List<String> additionIds = labReqAdditions1.stream().map(LabReqAdditions::getAdditionReqId).distinct().collect(Collectors.toList());
            additionIds.add(labReqAdditions.getReqId());
            List<String> reqNos = this.listByIds(additionIds).stream().map(LabReqMain::getReqNo).distinct().collect(Collectors.toList());

            LambdaQueryWrapper<LabReqdetail> reqdetailWrapper = new LambdaQueryWrapper<>();
            reqdetailWrapper.in(LabReqdetail::getReqNo, reqNos);
            String feeName = labReqdetailMapper.selectList(reqdetailWrapper).stream().map(LabReqdetail::getFeeName).collect(Collectors.joining(", "));
            //修改检验目的
            LabReqMain reqMain = this.getById(labReqAdditions.getReqId());
            reqMain.setTestPurpose(feeName);
            this.updateById(reqMain);


            LambdaUpdateWrapper<LabMaininfo> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(LabMaininfo::getReqNo, reqMain.getReqNo());
            updateWrapper.set(LabMaininfo::getTestPurpose, feeName);
            labMaininfoMapper.update(null, updateWrapper);

            return Result.succ(1, "取消附加成功", labReqAdditionsDto);
        } else {

        }
        return Result.fail("取消附加失败！");
    }
}
